解释询问 'this' 在 Javascript 中的值 [英] Explanation asked about the value of 'this' in Javascript

查看:22
本文介绍了解释询问 'this' 在 Javascript 中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Javascript 中有这个类:

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]);
            }
        });
    }
}

initialize 方法中,我使用了一个promise.当这个承诺完成时,匿名函数被执行.在函数中,您会看到 that 的使用,它在第 4 行声明.当我使用 this 关键字而不是 that 时,this 指向 window,而 that 指向对象.

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?

推荐答案

this 的值取决于函数的调用方式,而不是函数的调用方式或位置是定义的.

The value of this is determined by how the function is called, not by how or where it is defined.

由于您将函数传递给某些第三方代码 (.then),因此您必须意识到调用该函数的不是,而是第三方代码,您将无法控制如何调用该函数.
在某些时候,回调很可能以大多数函数的调用方式被调用,就像

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()

在这种情况下,this 指的是全局对象,它恰好是浏览器中的 window (this如果函数处于严格模式,则为 undefined.

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).

有关 MDN 的更多信息.

这篇关于解释询问 'this' 在 Javascript 中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆