0

对我来说,使用私有成员并使用 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在类中的每个方法中使用这个变量而不将它定义为对象属性?

4

1 回答 1

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

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

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);
  }
}
于 2019-01-07T07:19:08.647 回答