How to correctly define a method for an object in JavaScript? The MDN shows example with prototype:
var Person = function (firstName) {
this.firstName = firstName;
};
Person.prototype.sayHello = function() {
console.log("Hello, I'm " + this.firstName);
};
var person1 = new Person("Alice");
// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"
But why I need to add methods outside the constructor if I can add it inside of it using this
:
var Person = function (firstName) {
this.firstName = firstName;
this.sayHello = function() {
console.log("Hello, I'm " + this.firstName);
};
};
var person1 = new Person("Alice");
// call the Person sayHello method.
person1.sayHello(); // logs "Hello, I'm Alice"
Are there any reasons to define method via prototype? And what the difference between these two approaches?