3

In ES6 (ECMAScript 2015) you can define a class method either in the constructor or the body, what's the difference?

class Person {
 constructor(name) {
   this.name = name;

   this.sayName = () => {
     console.log('hello i am', this.name);
   }
 }
}

class Person2 {
 constructor(name) {
   this.name = name;
 }

 sayName() {
   console.log('hello i am', this.name);
 }
}

My guess is, in Person, the method sayName is being recreated each time we instantiate a Person object, and in Person2, we are applying the method to the prototype? (just a guess)

Kevin Wu
  • 8,461
  • 5
  • 28
  • 28
  • 2
    Your guess is right. Always use the second option if you don't need additional information during instantiation. – Antiga Jan 06 '16 at 21:49
  • @Antiga is there a good example for when you might need additional information? – Kevin Wu Jan 06 '16 at 21:50
  • I mean if you are passing something in to the constructor that would modify how or which function you are attaching as a class method. Not a very good way to build a class, so I would be hard-pressed to find an example I would be happy with. Here's a good write-up: http://thecodeship.com/web-development/methods-within-constructor-vs-prototype-in-javascript/ -- same thing applies with ES2016 class. – Antiga Jan 06 '16 at 21:52
  • Classes are just syntactic sugar for constructor function + prototype. The same reasons apply. – Felix Kling Jan 06 '16 at 22:44

0 Answers0