2010-07-29 204 views
0

下面描述我的問題,請幫助:回調函數返回全局對象:/

var Land = function(){ 
    this.cities = []; 
} 
Land.prototype = { 
    addCity : function(city){ 
     this.cities.push(city); 
    } 
} 
var City = function(){ 
    this.val = "foo"; 
}; 
City.prototype = { 
    test : function(){ 
     this.val = "bar"; 
     console.log(this); 
    } 
} 


var myLand = new Land(); 
myLand.addCity(new City()); 

// this row return right - City Object - :) 
myLand.cities[0].test(); 

function callBack(fnc){ 
    fnc(); 
} 

// this row return fail - global object - :(
// i need return City Object as in the first case 
callBack(myLand.cities[0].test); 
​ 

回答

1

那是因爲你的callback函數直接調用fnc參數,並參考fnc不包含任何基本對象(fnc未綁定任何訪問對象)

有很多方法來避免這種情況,最簡單的國際海事組織,是使用一個匿名函數,並且有執行你的函數:

callBack(function() { 
    myLand.cities[0].test(); 
}); 

這樣,test中的this值將爲myLand.cities[0]對象。

有關this值在函數上的行爲的更多信息,請參閱this question

+0

非常感謝! – AHOYAHOY 2010-07-29 02:47:51