箭头函数this指向定义时的对象(另有call,apply,bind用法)

参考:

https://segmentfault.com/a/1190000009556703#articleHeader3

在ES6中,箭头函数this指向定义时的对象,省去了var that=this的麻烦,耶耶耶~~~

接下来我们来总结一下,在ES5中:

  1. this的值通常是由当前函数的执行环境所决定;

  2. 在全局作用域,this指向全局对象 (window对象);

  3. 当使用new关键字声明,this指向新建对象;

  4. 我们可以使用call()bind()apply()来设置this

  5. 箭头函数不会绑定this


对比:

箭头函数:

扫描二维码关注公众号,回复: 2248952 查看本文章

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





猜你喜欢

转载自blog.csdn.net/gytha_1/article/details/80619638