0

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);
​

1 Answer 1

1

That happens because your callback function invokes the fnc parameter directly, and the reference fnc doesn't contains any base object (fnc is 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:

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

In that way, the this value inside test will be the myLand.cities[0] object.

See this question for more info about the behavior of the this value on functions.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.