如何在JavaScript

时间:2015-12-25 11:00:39

标签: javascript oop

如何在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"

有没有理由通过原型定义方法?这两种方法有什么区别?

0 个答案:

没有答案