【问题标题】:Understanding "this" in Javascript理解 Javascript 中的“this”
【发布时间】:2012-01-11 03:43:50
【问题描述】:

我有 2 个代码块,一个不工作,另一个工作,因为我指定了 = this 并在我的函数中使用 that 而不是 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 指的是本地执行上下文。 (我 100% 肯定其他人可以说得比我好。)您的 that 变量是一个闭包,它捕获 this 的值,以便您可以在函数调用内部引用它,无论何时发生,在未来的某个时候。

标签: javascript


【解决方案1】:

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

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

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

【讨论】:

  • 谢谢!这是一个非常清晰的描述,对我来说很有意义。
【解决方案2】:

我认为link 将极大地帮助您了解 Javascript 中对象和私有成员的区别以解决您的问题,请查看 Private 部分。希望对您有所帮助!

【讨论】:

  • 我想你忘记了链接
  • 感谢您的评论,但我没有看到您的链接
【解决方案3】:

Mozilla 对此有一些很好的阅读。如果您希望它在不将 this 分配给 that 的情况下工作,您可以随时使用 call

示例:jsfiddle.net/5azde/

【讨论】:

    【解决方案4】:

    你可以永远记住这一点:

    当一个对象的函数被调用时,该对象将作为这个值传递(如分别属于“window”和“myObject”的“add”和“increment”函数)。如果函数不属于任何对象,窗口(或全局)将作为此值传递。(与示例代码中的函数助手一样)。

    我很高兴看到一个纯粹的 js 问题。没有 jQuery,没有 css,没有 dom 选择器。哈哈。

    愿它有所帮助。 :-)

    【讨论】:

    • 请注意,每个函数的 this 值都是定义好的,在函数形成时不可更改。但是你可以用'call'或'apply'函数修改'this'值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-04
    • 1970-01-01
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多