在模拟“类”时,为什么要在.prototype属性中而不是在构造函数本身中设置方法?

时间:2015-01-08 16:56:52

标签: javascript class object constructor prototype

我正在尝试理解JavaScript中的“类”。

通常在JavaScript中模拟类看起来像这样:

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";
}

MyClass.prototype.someMethod = function() {
    console.log("Hello!");
};

虽然在构造函数中设置了非函数成员,但是将该方法添加到构造函数之外的构造函数的.prototype属性中。

我想了解原因。为什么不在构造函数内部创建方法,就像其他成员一样?含义:

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";

    this.someMethod = function() {
        console.log("Hello!");
    }
}

2 个答案:

答案 0 :(得分:1)

以下是一些要点:

  • 性能:每次创建实例时都会创建Ctor方法,而原型方法只创建一次并且inherited.prototype在这里更好。
  • Ctor方法可以访问函数内部的私有函数,而原型函数则不会。

答案 1 :(得分:1)

  

为什么不在构造函数中创建方法,就像其他成员一样?

因为实例之间的方法通常不同。在您的示例中,每个实例都具有相同的 someMethod方法,执行完全相同的操作。因此,只有一次创建该方法才有意义。

另一方面,标量数据通常是特定的到实例(即实例之间不同),因此应该在构造函数中初始化。


FWIW,ECMAScript6引入了新的class语法,鼓励这种结构。

function MyClass(someParameter) {
    this.someValue = someParameter;
    this.someOtherValue = "green";
}

MyClass.prototype.someMethod = function() {
    console.log("Hello!");
};

相当于

class MyClass {
    constructor(someParameter) {
        this.someValue = someParameter;
        this.someOtherValue = "green";
    }

    someMethod() {
       console.log("Hello!");
    }
}