回调函数返回全局对象:/

时间:2010-07-29 02:24:28

标签: javascript prototype callback

请帮助我解决下面描述的问题:

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 个答案:

答案 0 :(得分:1)

这是因为您的callback函数直接调用fnc参数,而引用fnc不包含任何基础对象(fnc未绑定到任何可访问的对象对象)

有许多方法可以避免这种情况,最简单的IMO就是使用匿名函数,然后执行你的函数:

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

这样,this内的test值将成为myLand.cities[0]对象。

有关函数this值的行为的详细信息,请参阅this question