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
In the expression
obj.f()
this
within f
will be bound to the value of obj
(the expression on the left hand-side of the .
).
If a function is invoked "alone", i.e.
f()
then this
within f
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.
var g = obj.f.bind(obj);
f(); // success! this == obj
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 property f
from obj
. The context is set when you CALL the function, either with obj.f()
or f()
in f
exists in the global scope, in which case the context would be the global object.
Read the specs! :) http://www.ecma-international.org/ecma-262/5.1/#sec-10.3