为什么使用'prototype'进行javascript继承?

Lio*_*ior 7 javascript inheritance

JavaScript对象具有'prototype'成员以便于继承.但看起来,我们可以完美地生活,即使没有它,我也想知道,使用它有什么好处.我想知道什么是利弊.

例如,考虑以下(这里是jsfiddle):

function Base (name) {

    this.name = name;
    this.modules = [];
    return this;
}

Base.prototype =
{
    initModule: function() {
        // init on all the modules.
        for (var i = 0; i < this.modules.length; i++)
            this.modules[i].initModule();
        console.log("base initModule");
    }   
};

function Derived(name) {
       Base.call(this,name); // call base constructor with Derived context
}

Derived.prototype = Object.create(Base.prototype);

Derived.prototype.initModule = function () {
      console.log("d init module");
      //  calling base class functionality
      Base.prototype.initModule.call(this);
    }

var derived = new Derived("dname");
console.log(derived.name);
derived.initModule();
Run Code Online (Sandbox Code Playgroud)

一个问题是,为什么要使用"原型"?我们也可以这样做Derived = Object.create(Base);

例如(jsfiddle):

Base =
{
    initModule: function() {
        // init on all the modules.
        for (var i = 0; i < this.modules.length; i++)
            this.modules[i].initModule();
        console.log("base initModule",this.name);
    },
    init: function(name) {
        this.name = name; 
        this.modules = [];
    }
};

Derived = Object.create(Base);

Derived.initModule = function () {
      console.log("d init module");
      //  calling base class functionality
      Base.initModule.call(this);
    }
Derived.init("dname");
console.log(Derived.name);
Derived.initModule();
Run Code Online (Sandbox Code Playgroud)

Exp*_*lls 3

如果不使用原型,每个类都会重新定义方法。也就是说,在第二个示例new Base; new Base; new Base中将创建六个函数。这需要更多的时间和空间。 Derived还将创建自己的功能。

此外,您不能使用原型来动态更改每个实例的方法(或添加新方法),这可能很有帮助——尤其是跨模块。

然而,这并不是说您应该始终为每个方法使用原型。每种情况都不同。

prototype还允许您在不同的上下文中调用方法,而无需创建实例(就像在Array.prototype.forEach.call类似数组的对象上一样)。