class My {
constructor() {
this.myMethod1 = function(){};
}
myMethod2() {
}
}
So is there any difference between myMethod1 and myMethod2?
class My {
constructor() {
this.myMethod1 = function(){};
}
myMethod2() {
}
}
So is there any difference between myMethod1 and myMethod2?
Yes. Defining the method inside the constructor results in the function being created and assigned when the object is first constructed, whereas defining it in the class body results in the method being added to the class's prototype.
class My {
constructor() {
this.myMethod1 = function(){};
}
myMethod2() {
}
}
console.log(My.prototype.myMethod1) //=> undefined
console.log(My.prototype.myMethod2) //=> function myMethod2() { ... }
Practically speaking, it's usually preferable to keep method definitions in the class body both for performance reasons and overall readability and semantic correctness. There may be some edge cases where it might make sense to assign methods in the constructor like that, but in my experience they're pretty rare.
For more detailed information on the technical differences between assigning methods to the prototype vs in the constructor, see Use of 'prototype' vs. 'this' in JavaScript?