JavaScript對象具有「原型」成員來促進繼承。但看起來,即使沒有它,我們也可以生活得很好,我想知道,使用它有什麼好處。我想知道有什麼優點和缺點。爲什麼使用'原型'的JavaScript繼承?
例如,請考慮以下的(這裏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();
一個問題是,爲什麼用 '原型' 呢?我們也可以這樣做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();
一個職業是速度:http://jsperf.com/prototype-vs-non-prototype/11 – StuR 2013-03-07 16:16:29
如果你有4級繼承?你會聲明一個newnewnewInitModule方法? – mpm 2013-03-07 16:24:44
@mpm你是對的,是一個錯誤,我編輯了這個 – Lior 2013-03-07 16:43:51