In the following code, I'm wondering how context is bound to this
:
In obj.myMethod();
, context is given to the object. So logging it gives the object.
In var myFun = obj.myMethod;
then myFun();
, context is given to the Window.
The only difference is you're setting the function to a variable.
var obj = {
myMethod : function () {
console.log(this); //'this' is bound to context of object
}
};
obj.myMethod(); //calling object property directly = Object {myMethod: function}
var myFun = obj.myMethod;
myFun(); //but setting obj method property to a variable and running gives Window as context
EDIT:
Following this melonJS tutorial, I'm confused how this callback is used (Scroll down to Part 2: Loading our level, you will see complete code)
// Set a callback to run when loading is complete.
me.loader.onload = this.loaded.bind(this);
I read this tutorial on callbacks, so I understand what they're used for... But I don't understand. It says this.loaded.bind(this)
What is the difference between this first and second this
statements? Aren't they the same? Why do I need to call this
then .loaded.bind()
then pass in this
again?
So, in your example, you say I can keep context by doing var bindMe = obj.myMethod.bind(obj);
, and in this case, you're using this
because you're already within the object game
? So this
refers to the owner game
?
Thank you
Short answer
In the expression
this
withinf
will be bound to the value ofobj
(the expression on the left hand-side of the.
).If a function is invoked "alone", i.e.
then
this
withinf
is bound to the global object (in the browser, window).That said, you can set the context before hand using the
.bind
function, i.e.c.f. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
You might also want to take a look at the
.call
and.apply
functions.Key point: functions DO NOT carry a context around.
obj.f
is a member access, all it does is return the value of the propertyf
fromobj
. The context is set when you CALL the function, either withobj.f()
orf()
inf
exists in the global scope, in which case the context would be the global object.Long answer
Read the specs! :) http://www.ecma-international.org/ecma-262/5.1/#sec-10.3