1

What is the difference between these functions? And what are the advantages and disadvantages?

let Test = function(name) {
  this.name = name;
  this.complete = function() {
    console.log(`completing task${this.name}`)
  }
}

and

let Test = function(name) {
  this.name = name;
}

Test.prototype.complete = function() {
  console.log(`completing task${this.name}`)
}
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
Murad Sofiyev
  • 790
  • 1
  • 8
  • 25

1 Answers1

2

The difference is that each object you will create with the first function would have it's separate instance of complete function. While each object you will create with the second function would share the same complete function, which can be found at the prototype of the object you create using Test.

So if you create 100 objects using the first function, all these objects would have a different reference in memory for the complete function. While in the second case you would have only one, since all these objects would find the complete function on their prototype.

Christos
  • 53,228
  • 8
  • 76
  • 108