理解“这个”在Javascript中 [英] Understanding "this" in Javascript

查看:85
本文介绍了理解“这个”在Javascript中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个代码块,一个不起作用,一个有效,因为我分配了= this并在我的函数中使用它而不是这个。有人可以帮助我理解为什么会这样。如果我正确地说(如果没有,请启发我),知道如何考虑如何在JavaScript中的对象函数中访问变量以及this的性质将有所帮助。谢谢!

I have 2 blocks of code, one that does not work, and one that works because I assign that = this and use that in my function instead of this. Can someone help me understand why this is so. It would help to know how one should think of accessing variables in functions in objects in JavaScript, and the nature of "this", if I am saying that right (if not, please enlighten me). Thank you!

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**


推荐答案

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

The first one doesn't work because when each function's this depends on how it was called.

首先你执行 myObject.double2()以及 this = myObject 。但是在 double2 里面,你自己调用 helper()并且你没有在它下面调用它的对象(它是不是 myObject.helper())。所以默认为全局对象(或窗口对象在浏览器中。

First you do myObject.double2() and so this = myObject. But inside double2, you call helper() by itself and there is no object you're calling it under (it's not myObject.helper()). So this defaults to the global object (or window object in a browser).

在第二个示例中,您捕获对 myObject的引用 that = this = myObject )所以 that.value = myObject.value

In the second example, you "capture" a reference to myObject (that=this=myObject) and so that.value=myObject.value.

这篇关于理解“这个”在Javascript中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆