John
John

Reputation: 1123

How to pass the this arg to javascript function

I have this code

var a = {
    b: function(){
        this.c();
    },
    c: function(){
        console.log("here");
    }
}

var x = {
    y: function(callback){
        callback();
    }
}

how to I pass the this argument so it works fine when i call x.y(a.b) ? I mean I want to access all members of "a" object when I call a.b as a result of passing it as a argument to x.y

Upvotes: 0

Views: 74

Answers (2)

Massimo Franciosa
Massimo Franciosa

Reputation: 554

you need to pass the reference to the a object to the function y. this is because when you pass the function a.b you don't tell javascript to pass the function b called from the object a but just the reference to the function. what i would do is to use the "call" function, that allow to set the "this" property of the function you want to call:

var x = {
y: function(callback,objFrom){
    callback.call(objFrom);
    }
}

and then:

x.y(a.b,a);

to clear your mind how "this" means in javascript you can read this article that was really useful to me: http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to bind the context manually,

x.y(a.b.bind(a));

If you do not bind it, then the this inside of a.b function will be considered as x

Upvotes: 3

Related Questions