0

Suppose that we are defining a Person constructor and creating a new person like that:

function Person(name){
    this.name = name;
}
var person = new Person("John Doe");

The following 2 implementations outputs: Hello from John Doe:

1st implementation

person.sayHello = function(){console.log("Hello from " + this.name);}

Running code 1

function Person(name){this.name = name;}
var person = new Person("John Doe");
person.sayHello = function(){console.log("Hello from " + this.name);}
person.sayHello();

2nd implementation

Person.prototype.sayHello = function(){console.log("Hello from " + this.name);}

Running code 2

function Person(name){this.name = name;}
var person = new Person("John Doe");
Person.prototype.sayHello = function(){console.log("Hello from " + this.name);}
person.sayHello();

My question is:

  1. As the results are similar, when it's better to add the property directly to the created object?
Ala Eddine JEBALI
  • 7,033
  • 6
  • 46
  • 65

1 Answers1

1

In simple words, using the prototype of an object is used to extend the object properties after they are created. One of the best use cases is, when the class is not written by you, or importing from somewhere, and you need to extend it.

Are the 2 implementations similar (I'm not talking about the result but for side effects)?

AFAIK, it's same.

If no, what are the differences and when we should choose the first one or the second one?

It's yes, but when to use, see above.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252