Skip to content Skip to sidebar Skip to footer

Google Closure Bind / Resolve Issues With The This Keyword

What is the Google Closure's solution for resolving the issues with the this keyword in JavaScript callback functions. It would be so useful in OO style programming. Is there any c

Solution 1:

goog.bind is the general purpose solution. For example:

goog.bind(this.someFunction, this);
goog.bind(this.someFunction, this, arg1);
goog.bind(this.someFunction, this, arg1, arg2);

The framework is generally designed such that this can be avoided, so it's not common to have to explicitly call goog.bind.

For example, goog.events.EventHandler automatically binds callbacks to the handler you set in its constructor.

var handler = new goog.events.EventHandler(this);
handler.listen(something, 'something', this.someFunction); // no need to bind

The array functions also support a handler argument.

goog.array.forEach(elements, this.someFunction, this);
var items = goog.array.map(elements, this.someFunction, this);

And so on. Most parts of the framework make it pretty easy to do this, it's very well designed for "pseudo-classic" inheritance.

For more details, see http://www.bolinfest.com/javascript/inheritance.php

Post a Comment for "Google Closure Bind / Resolve Issues With The This Keyword"