無法弄清楚如何從父對象的回調中訪問子對象的「擴展」屬性。我的兩次嘗試都在下面。我希望函數「say_something」提醒「說聲嗨」,其中「hi」來自孩子。相反,它說「說未定義」。JavaScript:當B從A繼承時,A中的回調看不到B
嘗試1:我創建一個對象「a」,然後創建一個從它派生的新對象「b」。但在「a」(這裏來自setTimeout)中的回調將無法訪問正確的「this」。
var a = {};
a.say_something = function() { setTimeout(function() { alert("say " + this.text); }, 0); };
var b = Object.create(a);
b.text = "hi";
b.say_something(); // alerts "say undefined"
嘗試2:通用智慧說重新安排允許可以在回調中訪問的「那個」變量。但是,與「這個」,「那個」不能從「B」訪問屬性:
var a = (function() {
var that = {};
that.say_something = function() { setTimeout(function() { alert("say " + that.text); }, 0); };
return that;
}());
var b = (function() {
var that = Object.create(a);
that.text = "hi";
return that;
}());
b.say_something(); // alerts "say undefined"
PS,我用道格拉斯Crockford的功能的Object.create代替(迷惑我)新()的。它複製到此處:
if (typeof Object.create !== "function") {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
「保存對* this * this的引用」是什麼。謝謝!爲了讓我的「嘗試2」代碼正常工作,我添加了* second *「var that = this;」正如你所建議的那樣,在setTimeout的調用之前。 (它會陰影/「覆蓋」第一個「var that = {};」,我將繼續在其他地方使用它) – 2010-12-11 01:10:21