2
class My {

  constructor() {
    this.myMethod1 = function(){};
  }

  myMethod2() {

  }
}

So is there any difference between myMethod1 and myMethod2?

Stepan Suvorov
  • 25,118
  • 26
  • 108
  • 176
  • In the first case each time you create new object new function will be created and in the second only one function will exists no matter how many objects you create. – jcubic Feb 04 '16 at 15:35
  • 2
    possible duplicate of [Use of 'prototype' vs. 'this' in JavaScript?](http://stackoverflow.com/q/310870/1048572) – Bergi Feb 04 '16 at 15:41

1 Answers1

10

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?

Community
  • 1
  • 1
Ajedi32
  • 45,670
  • 22
  • 127
  • 172