【问题标题】:var that = this - can you please help me understand [duplicate]var that = this - 你能帮我理解吗[重复]
【发布时间】:2012-06-05 03:50:51
【问题描述】:

可能重复:
What does var that = this; mean in javascript?

我经常在 Javascript 代码中找到这个作业:

var that = this;

这是一个例子:

function Shape(x, y) {
    var that= this;

    this.x = x;
    this.y = y;

    this.toString= function() {
        return 'Shape at ' + that.x + ', ' + that.y;
    };
}

您能解释一下为什么需要这样做吗?

请记住,我非常熟悉 PHP 或 Java,但不熟悉 Javascript 对象模型。

【问题讨论】:

标签: javascript


【解决方案1】:
  • Shape 是一个 JavaScript 类。它有成员 toString() 和私有属性 this.x
  • this 指的是当前类实例。
  • 为了让 toString() 意识到它是在“当前类实例”下运行的,您将其赋值为 = this。因为变量 'that' 可以在 toString() 的范围内访问。这就是所谓的“我”运算符。

【讨论】:

  • 嗯。严格来说,JS 中没有类。 Shape 是一个构造函数。而且私有属性也不存在,所有属性都可以被任何引用该对象的代码公开访问。
【解决方案2】:

this的值是在调用函数时设置的。

that 设置为this 会为该函数内部定义的函数保留该值(因为否则它将获得this 的值,这取决于it(内部函数) 被调用。

【讨论】:

    【解决方案3】:

    它使内部函数可以访问调用了 Shape() 方法的实例。这种类型的变量访问称为“闭包”。更多详情请看这里:https://developer.mozilla.org/en/JavaScript/Guide/Closures

    【讨论】:

      【解决方案4】:

      构造函数中的this 指的是将从它构建的对象。但是,它的方法中的this 可能不再引用同一个对象。

      因此,我们通过将this 保留到变量that 中来解决这个问题。这样,我们仍然可以在不使用this 变量的情况下引用创建的对象。

      function Shape(x, y) {
          var that= this;
      
          this.toString= function() {
              //"this" in here is not the same as "this" out there
              //therefore to use the "this" out there, we preserve it in a variable
          };
      }
      

      【讨论】:

        猜你喜欢
        • 2012-09-04
        • 2017-09-18
        • 2021-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-02
        • 2014-10-13
        相关资源
        最近更新 更多