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:
- As the results are similar, when it's better to add the property directly to the created object?