1. 程式人生 > 程式設計 >JavaScript哪些場景不能使用箭頭函式

JavaScript哪些場景不能使用箭頭函式

1. 定義物件方法

  js 中物件方法的定義方式是在物件上定義一個指向函式的屬性,當方法被呼叫的時候,方法內的 this 就會指向方法www.cppcns.com所屬的物件。

let obj = {
    array: [1,2,3],sum: () => {
        console.log(this === window); // true
        return this.array.reduce((result,item) => result + item);
    }
};
console.log(this === window); //true
obj.sum();//報錯:Uncaught TypeError: Cannot read property 'reduce' of undefined at Object.sum

  執行時 this.array 是未定義的,呼叫 obj.sum 的時候,執行上下文裡面的 this 仍然指向的是 window,原因是箭頭函式把函式上下文繫結到了 window 上,this.array 等價於 window.array,顯然後者是未定義的。

  修改方式:使用函式表示式或者方法簡寫(ES6 中已經支援)來定義方法,這樣能確保 this 是在執行時是由包含它的上下文決定的。程式碼如下:

let obj = {
    array: [1,sum() {
        console.log(程式設計客棧this === window); // false
        return this.array.reduce((result,item) => result + item);
    }
};
console.log(this === window); //true
console.log(obj.sum());//iJNgPM
6

2.定義原型方法

  同樣的規則適用於原型方法(prototype method)的定義,使用箭頭函式會導致執行時的執行上下文錯誤。比如下面程式碼:

function Cat(name) {
    this.name = name;
}

Cat.prototype.sayCatName = () => {
    console.log(this === window); // => true
    return this.name;
};

const cat = new Cat('Tom');
console.log(cat.sayCatName()); // undefined

  使用傳統的函式表示式就能解決問題,程式碼如下所示:

function Cat(name) {
    this.name = name;
}

Cat.prototype.sayCatName = function () {
    console.log(this === window); // => false
    return this.name;
}

const cat = new Cat('Tom');
console.log(cat.sayCatName()); // Tom

  sayCatName 變成普通函式之後,被呼叫時的執行上下文就會指向新建立的 cat 例項。

3. 定義事件回撥函式

  箭頭函式在宣告的時候就綁定了執行上下文,要動態改變上下文是不可能的,在需要動態上下文的時候它的弊端就凸顯出來。

  比如在客戶端程式設計中常見的 DOM 事件回撥函式(event listenner)繫結,觸發回撥函式時 this 指向當前發生事件的 DOM 節點,而動態上下文這個時候就非常有用,比如下面這段程式碼試圖使用箭頭函式來作事件回撥函式。

const button = document.getElementById('myButton');
button.addEventListener('click',() => {
    console.log(this === window); // true
    this.innerHTML = 'Clicked button';
});

  在全域性上下文下定義的箭頭函式執行時 this 會指向 window,當單擊事件發生時,this.innerHTML 就等價於 window.innerHTML,而後者是沒有任何意義的。

  使用函式表示式就可以在執行時動態的改變 this,修正後的程式碼:

const button = document.getElementById('myButton');
button.addEventListener('click',function () {
    console.log(this === button); // true
    this.innerHTML = 'Clicked button';
});

4. 定義建構函式

  建構函式中的 this 指向新建立的物件,當執行 new Car() 的時候,建構函式 Car 的上下文就是新建立的物件,也就是說 this instanceof Car === true。顯然,箭頭函式是不能用來做建構函式, 實際上 JS 會禁止你這麼做,如果你iJNgPM這麼做了,它就會丟擲異常。

  比如下面的程式碼就會報錯:

cwww.cppcns.comonst Message = (text) => {
    this.text = text;
};
const helloMessage = new Message('Hello World!');//報錯: Throws "TypeError: Message is not a constructor"

  構造新的 Message 例項時,JS 引擎拋了錯誤,因為 Message 不是建構函式。可以通過使用函式表示式或者函式宣告來宣告建構函式修復上面的例子。

const Message = function(text) {
    this.text = text;
};
const helloMessage = new Message('Hello World!');
console.log(helloMessage.text); // 'Hello World!'

以上就是javascript哪些場景不能使用箭頭函式的詳細內容,更多關於javaScript不能使用箭頭函式的資料請關注我們其它相關文章!