在Javascript中理解“this”

时间:2012-01-11 03:43:50

标签: javascript

我有2个代码块,一个不起作用,一个有效,因为我分配了= 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**

4 个答案:

答案 0 :(得分:4)

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

首先,您执行myObject.double2(),然后执行this = myObject。但是在double2内,你自己调用helper()并且没有任何对象你正在调用它(它不是myObject.helper())。因此this默认为global对象(或浏览器中的window对象)。

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

答案 1 :(得分:2)

我认为这个link可以帮助您理解Javascript中对象和私有成员之间的差异以解决您的问题,请查看私有部分。希望它有所帮助!

答案 2 :(得分:1)

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

示例:jsfiddle.net/5azde /

答案 3 :(得分:0)

你可以永远记住这一点:

  

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

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

愿它有所帮助。 : - )

相关问题