Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the parent object of a callback function

I have a function:

myObject.myFunction = function(callback){
  callback();
}

and a callback

randomObject.callBack = function(){
  console.log(this);
}

if I call randomObject.callBack() directly, I get the parent object in the console. However, if I call myObject.myFunction(randomObject.callBack), it logs a DOM Element.

How can I access the parent object?


Note

I do not know the name of the callbacks parent object ahead of runtime.

like image 815
Mild Fuzz Avatar asked Jan 19 '26 22:01

Mild Fuzz


1 Answers

The context (i.e. this value) of an object is determined at the time the function is run, not at the time it is defined. Passing randomObject.callBack to another function does not send the context (the randomObject bit); it just sends the function.

Presumably the context is set when myFunction calls it. Since you aren't explicitly providing a context (e.g. with call or apply), the context will be the window object.

You can change this by explicitly saying what the context of the function should be before it is run. You can do this with the bind method:

myObject.myFunction(randomObject.callBack.bind(randomObject))

Now when you call callback inside myFunction, randomObject will be logged.

Note that bind is relatively new; not all browsers support it. The MDN page I linked to above has a bit of code that will make it work in all browsers.

like image 64
lonesomeday Avatar answered Jan 22 '26 12:01

lonesomeday