6

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);
    }
  }
}
Deadpool
  • 7,811
  • 9
  • 44
  • 88

2 Answers2

2

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
unional
  • 14,651
  • 5
  • 32
  • 56
  • Which leads to the next question: what is the advantage of the 1st over the 2nd (if any)? – mac Jun 04 '23 at 17:36
  • Not much reason to use the 2nd way. There might be some very corner cases (e.g. some self-enclosed polymorphic functions). 99.9% of the time you should use the first one. – unional Jun 05 '23 at 18:22
0

There are a few differences but the most important in my opinion is that when you add a class method, TypeScript will transpile it to be a so-called prototype method, which is kind of shared for all object instances. On the other hand, adding the method to the object in the constructor will add it only to that object instance, possibly overwriting any prototype method with the same name.

Each scenario might have its use-cases, but in my experience, most of the times you should prefer the prototype methods, so in TypeScript, class methods. Also it fits more into TypeScript's OO world.

You can read more about prototype members versus object members for example here.

Another difference is that the Class 2 example might not even be valid TypeScript code (depending on version I guess), because basically you're dynamically adding the method to the instance, and not statically declaring it in the class. Even if you can make it valid TypeScript (e.g. using hacks like casting to any), I'm pretty sure you will loose for example editor intellisense for the method printData.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93