Explanation asked about the value of 'this' in Javascript [duplicate]

試著忘記壹切 提交于 2019-12-02 08:09:06

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

someFunction()

In that case, this refers to the global object which happens to be window in browsers (this is undefined if the function is in strict mode).

More information on MDN.

The callback you pass to the promise gets called asynchronously. In that case, this refers to the default context, which is the global window in the browser, and module 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)

this.initialize = function () {
    settings.listFn().then(function (response) {
        angular.copy(response, items);

        if (response.length > 0) {
            that.setCurrentItem(response[0]);
        }
    }.bind(this));
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!