ES6:箭頭函數以及this

ES6的箭頭函數應該是ES6標準裏我接觸比較多的,看過幾篇文章,現在對箭頭函數自己做一個總結。
阮一峯老師的ES6介紹裏面的《函數的擴展》關於箭頭函數的介紹,還是相當詳細。
結合從 use strict 看 JS(一):this 與箭頭函數一文,寫寫我關於箭頭函數的理解。


this的調用方式

  • 函數作爲對象方法,在對象方法內使用this
var obj = {
    name: 'objName',
    getName: function(){
        return this.name;// 在此處使用this,叫做方法調用
    }
}
  • 在函數裏面調用
function func(){
    return this.name;
}

這裏的this指向的是window對象(如果是在全局調用的話),但在嚴格模式裏,這個this表示undefined。

  • 在構造函數中使用,構造函數與普通函數的區別就是new關鍵字。
function constructor(name){
    this.name = name;
}
var amy = new constructor('Amy');

this指向的是new出來的對象實例。

  • 使用apply/call/bind改變this指向

箭頭函數

主要的用法就不再說了,說說其特點和需要注意的地方。

  • 函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
    這裏可以使用ES6和ES5的兩種方式,看看實現效果
//ES6
function timer(){
    setTimeout(()=>{console.log(this.name);}, 1000);
}
timer.call({name: 'amy'}); //輸出amy

//ES5
name = 'tom';
function timer(){
    setTimeout(function(){console.log(this.name)}, 1000);
}
timer.call({name: 'amy'}) //輸出tom

箭頭函數可以讓setTimeout裏面的this,綁定定義時所在的作用域,而不是指向運行時所在的作用域。

  • 箭頭函數裏沒有this

箭頭函數中,沒有this。如果你在箭頭函數中使用了this,那麼該this一定就是外層的this。

//錯誤, this爲undefined/window
const person = {
    name: 'tom',
    getName: ()=>this.name;// == return undefined.name/window.name
}
// 可以稍做改動
const person = {
    name: 'tom',
    getName: function() {
        return setTimeout(() => this.name, 1000);
    }
}

// 編譯之後變成
var person = {
    name: 'tom',
    getName: function getName() {
        var _this = this;  // 使用了我們在es5時常用的方式保存this引用

        return setTimeout(function () {
            return _this.name;
        }, 1000);
    }
};

爲什麼第一個代碼段裏的this爲undefined呢?
是因爲,箭頭函數默認使用的是嚴格模式,嚴格模式中是匿名函數中的this指向的不再是window了,而是undefined。
即便不是undefined,那也是window。
箭頭函數裏面根本沒有自己的this,而是引用外層的this。

  • 不存在arguments參數

在箭頭函數中是沒有arguments參數的,這點和this一樣。

function getMsg(msg){
    setTimeout(()=>console.log(arguments[0]));
}
getMsg('hi');//輸出hi
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章