箭头函数this指向的实践

timg.jpg

先上一波代码福利;(__) 嘻嘻……

<code>
//箭头函数表示
function foo(){
console.log(this.id);
return ()=>{
console.log(this.id);
return ()=>{
console.log(this.id);
return ()=>{
console.log(this.id);
}
}
}
}
var f=foo.call({id:1});
f.call({id:2})()();
f().call({id:3})();
f()().call({id:4});
//输出为10个1
</code>

<code>
//正常函数表示
function foo(){
console.log(this.id);
return function(){
console.log(this.id);
return function(){
console.log(this.id);
return function(){
console.log(this.id);
}
}
}
}
var f=foo.call({id:1});
f.call({id:2})()();
f().call({id:3})();
f()().call({id:4});
//输出为1、2、undefined、undefined、undefined、3、undefined、undefined、undefined、4

</code>

箭头函数是没有自己的<code>this</code>值,只能继承外围作用域,也就是<code>foo</code>。

正常情况下,<code>foo</code>的<code>this</code>指向<code>window</code>,因为<code>foo.call({id:1})</code>这句代码,<code>foo</code>的<code>this</code>指向转移到了<code>{id:1}</code>。

所以箭头函数中的<code>this.id</code>全部是 1;

而正常函数中,所有的<code>this</code>指向都是<code>window</code>,经过<code>foo.call({id:1})、f.call({id:2})、f().call({id:3})、f()().call({id:4})</code>

的代码处理之后,各自<code>this</code>指向都变为了自己指定的那个对象,所以<code>this.id</code>如上面结果所示。

有说的不对地方欢迎各位指正!

<blockquote>关于apply、call的使用 http://blog.csdn.net/business122/article/details/8000676</blockquote>
<blockquote>ECMAScript6入门.pdf</blockquote>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,567评论 19 139
  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 12,385评论 2 17
  • 与其他语言相比,函数的this关键字在JavaScript中的表现略有不同,此外,在严格模式和非严格模式之间也会有...
    codingC阅读 3,635评论 0 0
  • 1.函数参数的默认值 (1).基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。
    赵然228阅读 4,037评论 0 0
  • Javascript 中的 this,有时候让人迷惑,所以总结了一下关于this指向的问题。 在函数中 this ...
    lxt410725阅读 3,258评论 0 1