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.
The context (i.e.
thisvalue) of an object is determined at the time the function is run, not at the time it is defined. PassingrandomObject.callBackto another function does not send the context (therandomObjectbit); it just sends the function.Presumably the context is set when
myFunctioncalls it. Since you aren’t explicitly providing a context (e.g. withcallorapply), the context will be thewindowobject.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
bindmethod:Now when you call
callbackinsidemyFunction,randomObjectwill be logged.Note that
bindis 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.