Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/469.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript ES6 Arrow函数与ES5:如何知道在使用ES5非Arrow函数时将'this'绑定到哪个函数_Javascript_Ecmascript 6_Ecmascript 5_Arrow Functions - Fatal编程技术网

Javascript ES6 Arrow函数与ES5:如何知道在使用ES5非Arrow函数时将'this'绑定到哪个函数

Javascript ES6 Arrow函数与ES5:如何知道在使用ES5非Arrow函数时将'this'绑定到哪个函数,javascript,ecmascript-6,ecmascript-5,arrow-functions,Javascript,Ecmascript 6,Ecmascript 5,Arrow Functions,我正在阅读ES6箭头函数的使用。它给出了以下示例,其中必须使用bind(this),然后是带有箭头函数的相应代码 var obj = { id: 42, counter: function counter() { setTimeout(function() { console.log(this.id); }.bind(this), 1000); } }; 在ES5示例中,它表示,.bind(this)是帮助将此上下文传递到函数中所必需的 我想知道的是:为

我正在阅读ES6箭头函数的使用。它给出了以下示例,其中必须使用
bind(this)
,然后是带有箭头函数的相应代码

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }.bind(this), 1000);
  }
};
在ES5示例中,它表示,.bind(this)是帮助将此上下文传递到函数中所必需的

我想知道的是:为什么要使用
bind(this)
来回调
setTimeout
,而不是使用
counter
函数?ie为什么上面的代码不是这样的:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
为什么将
bind(this)
setTimeout
的回调一起使用,而不是与counter函数一起使用

因为
计数器
函数(其工作方式类似于
obj
对象的方法)已经具有适当的
this
,因为您像
obj.counter()
一样调用它,所以它从调用它为
obj.counter()
中获得
this
。假设将计数器调用为
obj.counter()
,那么如果在
counter()
函数的第一行执行
console.log(this.id)
,它将正确显示
id

但是,传递给
setTimeout()
的回调没有自然的
值,除非在回调函数本身上使用箭头函数或
.bind()
,因为当
setTimeout()
调用回调函数时,它不会设置特定的
值(它只是将回调函数作为正常函数调用)因此,
值变为默认值。这意味着
如果在
setTimeout()
回调中运行严格模式,则此
将是
未定义的
,如果在loosey-goosey模式下运行,则全局对象将是
未定义的

请参阅调用函数时设置此
值的6种方法


我还应该提到,如果你按照你的建议这样做:

var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};
var obj = {
  id: 42,
  counter: function counter() {
    setTimeout(function() {
      console.log(this.id);
    }, 1000);
  }.bind(this);
};

它不仅对
setTimeout()
回调毫无帮助,而且还会将
this
的错误值绑定到
counter()
方法。在
var obj
定义(也称为
this
的词法值)之前,您将得到
this
的任何内容。

可能值得一提的是,在对象中这样定义的函数通常被称为方法。这有助于更好地了解它们的使用/范围,我明白了,谢谢!同时感谢@Phil的留言。实际上,等等,我仍然不明白为什么在回调中使用
bind
会将
this
的值设置为
obj
,而在
计数器中使用它会将其设置为词法值。为什么不将其应用于
计数器
计数器
绑定到
obj
?@gkeenley-因为调用
obj.counter()
已经将
计数器
内部的
设置为
obj
。因此,当您使用
function(){}.bind(this)
setTimeout()
时,它将拾取
this
的值(所需值)。执行
.bind(this)
以计数器自身,获取当时起作用的
this
值,并为
计数器()设置该值。这有两个问题。首先,它是
this
的错误值(它不是
obj
),其次,它控制计数器作用域,而不是
setTimeout()
作用域的回调,这就是问题所在。好的,一切都明白了。我很感激。