1

可能重复:
什么 var that = this; 在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 对象模型。

4

4 回答 4

4

它使内部函数可以访问调用 Shape() 方法的实例。这种类型的变量访问称为“闭包”。有关更多详细信息,请参见此处:https ://developer.mozilla.org/en/JavaScript/Guide/Closures

于 2012-05-30T21:11:00.603 回答
4

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

设置thatthis保留该函数内部定义的函数的该值(因为否则它将获得一个值,this这取决于(内部函数)的调用方式。

于 2012-05-30T21:11:09.313 回答
0

构造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-05-30T21:10:08.377 回答
0
  • Shape 是一个 JavaScript 类。它有成员 toString() 和私有属性 this.x
  • this 指的是当前的类实例。
  • 为了让 toString() 意识到它在“当前类实例”下运行,您分配 that = this。因为变量 'that' 可以在 toString() 的范围内访问。这就是所谓的“我”运算符。
于 2012-05-30T21:11:14.237 回答