You can change this
of a particular function by using .bind()
:
function foo() {
alert(this.x);
}
var boundFoo = foo.bind({x: "bar"});
boundFoo();
This alerts "bar".
Saving the outer this
as realThis
or that
is also common if you want access to both the inner and outer this
.
Underscore uses .call()
to change this
of the iterator function you pass it. Specifically, _.each()
has a third parameter that allows you to specify what you want this
to be, so that example is correct. See the underscore.js source.