0

I am confused about one of the syntaxes in ES7. I define a class as:

class Employee2 {
  Ename = "Rahul";
  printName =  () => {
    console.log(this.Ename);
  }
}

Since classes are syntactical sugar over existing prototype concept, I expected that the method 'printName' would actually go to function prototype. But that did not happen, the method is an object property.

However, if I do:

class Employee {
  Ename = "Rahul";
  printName () {
    console.log(this.Ename);
  }
}

this works as expected where printName goes to the prototype. Now my query:

ES7 suggests using the syntax as in first code Employee2 class, if I use that I miss the method definition on the prototype. Is there a way to achieve the method on function prototype?

Rahul Agarwal
  • 41
  • 1
  • 7
  • *"ES7 suggests using the syntax as in first code Employee2 class"* Where did you read that? In the first, `printName` is an *own* property of the instance, just like `Ename`. [Class field proposal](https://github.com/tc39/proposal-class-fields) – adiga Sep 27 '19 at 11:54

1 Answers1

1

ES7 suggests using the syntax as in first code Employee2 class

No. Use if appropriate. I'd go with the second version as often as possible. The first version barely equals:

 function Employee2() {
   this.Ename = "Rahul";
   this.printName =  () => {
     console.log(this.Ename);
   };
 }
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151