了解在两种不同情况下“ this”的使用

时间:2018-10-12 20:25:46

标签: javascript

我不明白为什么在这种情况下“ this”返回“ NaN”:

function Counter() {
  this.num = 0;
  this.timer = setInterval(function add() {
    this.num++;
    console.log(this.num);
  }, 1000);
}

在此示例中,它指的是“ this.value”:

function foo() {
    this.value = 'Hello, world';

    this.bar = function() {
        alert(this.value);
    }
}

var inst = new foo();
inst.bar();

在第一种情况下,我知道“ this”指向Window对象,我只是不明白为什么会这样。

2 个答案:

答案 0 :(得分:1)

内部setInterval this将会是全新的,并且不会对Counter有所了解。您可以使用bind将上下文this传递给setInterval

function Counter() {
  this.num = 0;
  this.timer = setInterval(function add() {
    this.num++;
    console.log(this.num);
  }.bind(this), 5000);
}

Counter()

或者,您也可以使用箭头功能

function Counter() {
  this.num = 0;
  this.timer = setInterval(() => {
    this.num++;
    console.log(this.num);
  }, 5000);
}

Counter()

答案 1 :(得分:0)

setInterval函数几乎不像这样:

 function setInterval(callback, time, ...args) {
   // native complicated code
   callback(...args);
 }

这里重要的是调用(callback(...),因为JS通过调用函数的方式确定上下文。在第二个示例中,bar的上下文是inst,您将其称为inst.bar(),因此您直接告诉js this是什么。如果您调用函数直接功能,例如

 const bar = inst.bar; 
 bar(); // call without context

您未指定上下文,因此this默认为window