Following this melonJS tutorial, I'm stumped by a couple ways 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)
1) What is the difference between this first and second this
statements
2) what does doing bind
and passing in (this)
do?
Thank you
.bind(this)
sets the context of the function
If you only set it to this.loaded
, the context is not preserved
This might make a little more sense
var cntx = this;
me.loader.onload = function() {
cntx.loaded();
}
However, in this example, no arguments are passed to the loaded
function. By using the bind
one-liner, you preserve context, and you don't have to worry about any arguments being dropped along the way.
Read about Function.prototype.bind here