参考:
https://segmentfault.com/a/1190000009556703#articleHeader3
在ES6中,箭头函数this指向定义时的对象,省去了var that=this的麻烦,耶耶耶~~~
接下来我们来总结一下,在ES5中:
this
的值通常是由当前函数的执行环境所决定;在全局作用域,
this
指向全局对象 (window
对象);当使用
new
关键字声明,this
指向新建对象;我们可以使用
call()
,bind()
,apply()
来设置this
;箭头函数不会绑定
this
对比:
箭头函数:
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });
// id: 42
非箭头函数:
function fo() {
setTimeout(function() {
console.log('id:', this.id);
}, 100);
}
var id = 21;
fo.call({ id: 42 });
// id: 21