我試圖在Javascript中理解原型繼承,但未能應用於以下情況。任何幫助,將不勝感激。Javascript中的原型鏈未更新
我定義構造函數如下:
var base = function() {
var priv = "private"; // Private
var publ = "public"; // Public through a getter/setter (below)
// The object to return
var f = {};
f.publ = function (new_val) {
if (!arguments.length) {
return publ;
}
publ = new_val;
return f;
};
return f;
};
有了這個構造,我可以通過調用base();
創建對象。這些對象有一個公共方法(publ)。現在
,以下相同的結構,我想有一個創建上述定義由「基地構造」創建的對象繼承對象的新構造:
var myclass = function() {
// Other parameters defined here
var f = function() {
// publ is inherited
console.log(f.publ());
};
// Trying to set the prototype of f to the object created by "base()"
f.prototype = base();
// Other methods defined here
return f;
};
隨着f.prototype = base();
我要讓˚F繼承由base()
返回的對象中定義的所有方法,但試圖調用f.publ抱怨,因爲 F沒有辦法了公佈
瞭解正在發生的事情將受到歡迎任何幫助
M;
原型繼承要求要麼'新'operator或'Object.create'。你在這裏沒有使用。 – Eric
這看起來不像一個構造函數。你可以使用帶'new'的構造函數。它看起來更像是一個模塊模式。 – elclanrs
正如在一些評論中指出的那樣,使用Object.create來設置繼承的原型部分並在Child中執行Parent.call(this,args)(這將處理從Parent繼承的instace成員)。這裏有更多信息http://stackoverflow.com/a/16063711/1641941 – HMR