先上一波代碼福利尝抖;(__) 嘻嘻……
<code>
//箭頭函數(shù)表示
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>
//正常函數(shù)表示
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>
箭頭函數(shù)是沒有自己的<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>指向轉(zhuǎn)移到了<code>{id:1}</code>步鉴。
所以箭頭函數(shù)中的<code>this.id</code>全部是 1揪胃;
而正常函數(shù)中叁巨,所有的<code>this</code>指向都是<code>window</code>枯跑,經(jīng)過<code>foo.call({id:1})、f.call({id:2})滑绒、f().call({id:3})阳似、f()().call({id:4})</code>
的代碼處理之后骚勘,各自<code>this</code>指向都變?yōu)榱俗约褐付ǖ哪莻€對象,所以<code>this.id</code>如上面結(jié)果所示撮奏。
有說的不對地方歡迎各位指正俏讹!
<blockquote>關(guān)于apply、call的使用 http://blog.csdn.net/business122/article/details/8000676</blockquote>
<blockquote>ECMAScript6入門.pdf</blockquote>