我有 2 个代码块,一个不起作用,另一个有效,因为我分配了那个 = this 并在我的函数中使用它而不是 this。有人可以帮助我理解为什么会这样。如果我说的是对的(如果不是,请赐教),了解应该如何考虑在 JavaScript 中访问对象中的函数中的变量以及“this”的性质会有所帮助。谢谢!

var add = function (x, y) {
  return x + y;
  }

var myObject = {
  value: 0,
  increment: function (inc) {
    this.value += typeof inc === 'number' ? inc : 1;
    }
};

myObject.double2 = function () {
  // var that = this;

  var helper = function () {
    this.value = add(this.value, this.value)
  };

  helper();
};

myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 100, **FAILS**

以及修改后的代码:
var add = function (x, y) {
  return x + y;
  }

var myObject = {
  value: 0,
  increment: function (inc) {
    this.value += typeof inc === 'number' ? inc : 1;
    }
};

myObject.double2 = function () {
  var that = this;

  var helper = function () {
    that.value = add(that.value, that.value)
  };

  helper();
};

myObject.increment(100);
document.writeln(myObject.value); // Prints 100
myObject.double2();
document.writeln('<BR/>'); // Prints <BR/>
document.writeln(myObject.value); // Prints 200 - **NOW IT WORKS**

最佳答案

第一个不起作用,因为每个函数的 this 何时取决于它的调用方式。

首先你做 myObject.double2()this = myObject 。但是在 double2 内部,您自己调用 helper() 并且没有您正在调用它的对象(它不是 myObject.helper() )。所以 this 默认为 global 对象(或浏览器中的 window 对象)。

在第二个示例中,您“捕获”了对 myObject ( that=this=myObject ) 和 that.value=myObject.value 的引用。

关于javascript - 在 Javascript 中理解 "this",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8813871/

10-14 14:38
查看更多