Reference Object calling function in Javascript
I have a makeshift events system in JS and the attacher looks like this:
events.attach(events.NEW_TASK,this.update);
Where this.update
is a callback/handler/function. The problem is, when the dispatcher tries to call this handler, it loses it's original context. How can I bind the handler with the context of the object that calls the attach function without passing this
as an argument and using that?
Edit: I should also mention that it will be somewhat of a framework so it has to be simple for other d开发者_如何学Pythonevelopers so preferably not needing to store the context in another variable.
Another option, using the Function.prototype.bind
method, part of the new ECMAScript Standard:
events.attach(events.NEW_TASK, this.update.bind(this));
Until ECMAScript 5 has wide adoption in browsers, you could use your own implementation of Function.prototype.bind
:
function bind(func, thisObj) {
return function() {
func.apply(thisObj, arguments);
};
}
events.attach(events.NEW_TASK, bind(this.update, this));
You could store the reference of "this" in a local variable and try calling the function using it
var that = this;
events.attach( events.NEW_TASK, function( ) { that.update(); } );
精彩评论