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