如何使用es6'Class'语法定义私有成员并在类本身中使用它

时间:2019-01-07 07:12:52

标签: javascript class ecmascript-6

使用私有成员并将这些成员与ECMAScript5一起在类中使用对我来说真的很简单,但是我不知道如何使用类语法将其用于ECMAScript6。

在我的代码中,我尝试在构造函数中声明一个属性,并在方法中使用了该函数,但未定义。

class Employee {
    constructor(name, empId, workedHours, payment) {
        var discount = 0.28;    
        this.name = name;
        this.empId = empId;
        this.workedHours = workedHours;
        this.payment = payment;
    }

    monthlyWage() {
        return (this.workedHours * this.payment) + (this.workedHours * discount);
    }
}
emp1 = new Employee('CooreyMShapher', 12, 89, 900);

那么,有什么方法可以在类中的每个方法中使用此discount变量,而无需将其定义为对象属性?

1 个答案:

答案 0 :(得分:0)

一种选择是将整个类放在IIFE中,并在其中定义discount,以确保discount类可以看到Employee,但外面的任何东西都看不到:

const Employee = (() => {
  const discount = 0.28;
  return class Employee{
    constructor(name, empId, workedHours, payment){

      this.name = name;
      this.empId = empId;
      this.workedHours = workedHours;
      this.payment = payment;
    }

    monthlyWage(){
      return (this.workedHours * this.payment) + (this.workedHours * discount);
    }
  }
})();
const emp1 = new Employee('CooreyMShapher', 12, 89, 900);
console.log(emp1.monthlyWage());

请注意,目前有一个proposal使它看起来更漂亮-将来,您可以在类字段之前使用#来指示只有类本身可以看到变量:

class Employee{
  static #discount = 0.28;
  constructor(name, empId, workedHours, payment){
    this.name = name;
    this.empId = empId;
    this.workedHours = workedHours;
    this.payment = payment;
  }

  monthlyWage(){
    return (this.workedHours * this.payment) + (this.workedHours * Employee.#discount);
  }
}