2010-12-10 56 views
0

無法弄清楚如何從父對象的回調中訪問子對象的「擴展」屬性。我的兩次嘗試都在下面。我希望函數「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(); 
    }; 
} 

回答

2

如果添加

a.say_something(); 

給你第一個例子中它也將返回say undefined。問題是setTimeout不執行它在調用它的範圍中調用的代碼。

我們可以通過解決這個問題:

  1. 硬編碼到現有的對象alert('say ' + a.text);
  2. 使用call()apply(),以指定的功能應該執行上下文的引用。 (並且bind()也是 - 用於最新的平臺)。

方法#2是你正在尋找的。

var a = {}; 
a.text = "hello!"; 
function say_something() { 
    var that = this; // Save the reference to *this* this. 
    setTimeout(function() { console.log.call(that, "say " + that.text); }, 0); 
} 
a.say_something = say_something; 
a.say_something(); // say hello! 

var b = (function() { 
    var that = Object.create(a); 
    that.text = "hi there!"; 
    return that; 
}()); 

b.say_something(); // say hi there! 
+0

「保存對* this * this的引用」是什麼。謝謝!爲了讓我的「嘗試2」代碼正常工作,我添加了* second *「var that = this;」正如你所建議的那樣,在setTimeout的調用之前。 (它會陰影/「覆蓋」第一個「var that = {};」,我將繼續在其他地方使用它) – 2010-12-11 01:10:21

2

在setTimeout函數中,「this」始終引用Window對象。

我最常做的是一樣的東西(測試和工程)

a.say_something = function() { 
    var thisObj = this; 
    setTimeout(function() { 
     alert("say " + thisObj.text); 
    }, 0); 
}; 
+0

這是否解決親子問題呢? – 2010-12-10 22:21:17

相關問題