Reputation: 33
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?
Upvotes: 0
Views: 140
Reputation: 138477
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);
};
}
Upvotes: 1