0

It's really straightforward for me to use private members and use those members inside the class with ECMAScript5, however I don't understand how to get this thing worked with ECMAScript6 using class syntax.

In my code I've tried declaring a property inside constructor function and used the function in a method, but it gets undefined.

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

So, Is there any way I can use this discount variable inside every method in the class without defining it as an object attribute?

fiza khan
  • 1,280
  • 13
  • 24
yasmikash
  • 157
  • 2
  • 14
  • "*It's really straightforward for me to use private members and use those members inside the class with ECMAScript5*" - how exactly are you doing that? – Bergi Jan 07 '19 at 07:31

1 Answers1

0

One option would be to put the whole class in an IIFE, and define discount inside, to ensure that discount is viewable to the Employee class, but not by anything outside:

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

Note that there's currently a proposal to make this a lot nicer-looking - you may, in the future, be able to use # before a class field to indicate that only the class itself may see the variable:

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);
  }
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320