Can anyone tell which is the beat approach to write class methods in js and What are the pros and cons?
First Approach
class Dog {
constructor(name) {
this._name = name;
}
bark() {
console.log(`hello ${this._name}`);
}
}
Second Approach
class Dog {
constructor(name) {
this._name = name;
}
}
Dog.prototype.bark = function bark() {
console.log(`hello ${this._name}`);
}
Top comments (2)
I personally prefer the first approach, because:
superkeyword, you actually have to do it that way. Thesuperkeyword is only allowed in class expressions and object literals, so the second style will generate a syntax error if you try to use thesuperkeyword in the method.thiskeyword a bit more explicit.Dogclass. A few of them will need some help to understand that that's the case in the second example.It's important to realize though that there are some limitations to the first example:
Note also that neither example will work in Internet Explorer, Opera Mini, or old pre-Chrome Android browser versions. Overall market share for ES6 class support is just over 90% right now though, so unless you need Internet Explorer support, either will work.
Thanks for lovely reply.
After your reading your explanation, I think that the first approach is faster.