Please help with my problem described below:
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);
That happens because your
callbackfunction invokes thefncparameter directly, and the referencefncdoesn’t contains any base object (fncis not bound to any accessible object)There are many ways to avoid this, the most simple IMO, would be to use an anonymous function, and there execute your function:
In that way, the
thisvalue insidetestwill be themyLand.cities[0]object.See this question for more info about the behavior of the
thisvalue on functions.