I have this class in Javascript:
return function (settings) {
var items = [],
formHelper = new FormHelper(items),
that = this;
this.currentItem;
this.initialize = function () {
settings.listFn().then(function (response) {
angular.copy(response, items);
if (response.length > 0) {
that.setCurrentItem(response[0]);
}
});
}
}
In the initialize
method, I use a promise. When this promised is finished, the anonymous function is executed. Within the function you see the use of that
, which is declared at line 4. When I use the this
keyword instead of that
, this
points to window
, while that
points to the object.
I am wondering why this is. Could someone explain how this works? Why it behaves like this?
The callback you pass to the promise gets called asynchronously. In that case,
this
refers to the default context, which is the globalwindow
in the browser, andmodule
in node.js, for example.If you want to prevent this, use
.bind()
to set the context of the function to your liking. (Note: Without polyfill,.bind()
is not available until IE9)The value of
this
is determined by how the function is called, not by how or where it is defined.Since you are passing the function to some third party code (
.then
), you have to be aware that it is not you who calls the function, but the third party code, and you won't have any control over how the function is called.At some point the callback will most likely be called in the way that most functions are called, simply as
In that case,
this
refers to the global object which happens to bewindow
in browsers (this
isundefined
if the function is in strict mode).More information on MDN.