2010-07-29 146 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