Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in putting method in Constructor or Outside it in a Class (Gives same Result) [duplicate]

The following 2 snippets give same result. I wondered what is the real diffence in these 2 approaches and when should one be used instead of another way. Can someone help me out understanding the difference?

Case 1:

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

  printData(){
    console.log(this.name);
  }
}

Case 2 :

class Person{
  constructor(name){
    this.name = name;
    this.printData = function(){
      console.log(this.name);
    }
  }
}
like image 709
Deadpool Avatar asked Nov 06 '22 16:11

Deadpool


1 Answers

The different is instance property versus prototype.

When you define a function inside the constructor, each new instance gets a new function defined, akin to

{
  printData: function () { ... }
}

When you define the method in the class, it is defined in the prototype and shared by every instance.

i.e. with first approach,

const p1 = new Person('bob')
const p2 = new Person('rob')
p1.printData === p2.printData // false

with second approach

const p1 = new Person('bob')
const p2 = new Person('rob')
p1.printData === p2.printData // true
like image 134
unional Avatar answered Nov 09 '22 23:11

unional