在javascript类中模仿静态属性

时间:2016-10-14 14:11:43

标签: javascript class static ecmascript-6

在es6中保留类的属性以模拟静态属性的最佳方法是什么?

使用原型链中创建的属性是否安全?



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'));




1 个答案:

答案 0 :(得分:2)

安全吗?是。乱?是。更好的选择?你敢打赌。

你应该将你的计数器逻辑移出构造函数来清理它。尝试这样的事情:

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);
  }
}

请注意不要使用countincrementconstructorprototype等创建者名称,否则您可能会覆盖您的类属性。