请帮助我解决下面描述的问题:
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);
答案 0 :(得分:1)
这是因为您的callback
函数直接调用fnc
参数,而引用fnc
不包含任何基础对象(fnc
未绑定到任何可访问的对象对象)
有许多方法可以避免这种情况,最简单的IMO就是使用匿名函数,然后执行你的函数:
callBack(function () {
myLand.cities[0].test();
});
这样,this
内的test
值将成为myLand.cities[0]
对象。
有关函数this
值的行为的详细信息,请参阅this question。