sabithpocker
sabithpocker

Reputation: 15566

Mimic static property in javascript classes

What is the best way to keep a property for a class in es6 that mimics a static property?

Is it safe to use a property created in prototype chain?

class Employee {
  constructor(name, creator) {
    this.name = name;
    if(! (creator in Employee.prototype)){
       Employee.prototype[creator] = 0;
      }
    Employee.prototype[creator]++;
  }
  static count(creator) {
    return Employee.prototype[creator];
  }
}


var y = new Employee("Jack", "x");
var z = new Employee("John", "y");
var jh = new Employee("John", "y");

console.log(Employee.count('x'), Employee.count('y'));

Upvotes: 0

Views: 548

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51916

Safe? Yes. Messy? Yes. Better alternative? You bet.

You should move your counter logic out of your constructor to clean it up a little. Try something like this:

class Employee {
  static count(creator) {
    return Employee[creator] || 0;
  }

  static increment(creator) {
    Employee[creator] = Employee.count(creator) + 1;
  }

  constructor(name, creator) {
    this.name = name;
    Employee.increment(creator);
  }
}

Just mind not to use a creator name like count, increment, constructor, prototype, etc. or you could overwrite your class properties.

Upvotes: 2

Related Questions