cmutex
cmutex

Reputation: 1608

Javascript callbacks, refering to own object

Below is a very simplified version of my problem. Without changing the definition of object "o" and without using the name "obj", how can i refer to obj inside foo.

var obj = {
    foo: function () {
        alert(this.greet); // => undefined, obj.greet works but not feasible for my case
    },
    greet: "hi"
};

var o = {
    m: obj.foo
};

o.m();

Upvotes: 2

Views: 53

Answers (2)

Quentin
Quentin

Reputation: 943480

Create a new function that calls the old function with the correct context. The bind method will do this for you in sufficiently modern browsers.

var o = {
    m: obj.foo.bind(obj)
};

If you want to support legacy browsers:

var o = {
    m: (function (context) { 
        return function () { 
            context.foo(); 
        };
    }(obj))
};

Upvotes: 6

friedi
friedi

Reputation: 4360

If you don't want to or could not change the definition of the object o, you can do the following:

Instead of

o.m();

do

o.m.call(obj);

Upvotes: 0

Related Questions