JavaScript context

javascript, scope

Solution

The way to solve this problem is to pass in the object you're scoping "this" to, inside of the Test function...

function Test(fn, scope, args) {
    fn.apply(scope, args);
}

Test(User.Show, User, []);

Where the args array allows you to additionally pass in any arguments you may have. You could also leave the Test function as it is and just pass in an anonymous function...

Test(function() {User.Show()});

Problem

``` var User = { Name: "Some Name", Age: 26, Show: function() { alert("Age= "+this.Age)}; }; function Test(fn) { fn(); } Test(User.Show); ``` =============== Alert shown by code is "Age= Undefined". I understand as User.Show function is called from inside of Test(), refers 'this' of 'Test()' function rather than 'User' object. My question is if there is any way to solve this problem?

Original source