如何在JavaScript中正确定义对象的方法? MDN显示了原型示例:
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"
但是为什么我需要在构造函数之外添加方法,如果我可以使用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"
有没有理由通过原型定义方法?这两种方法有什么区别?