您的位置:首頁技術文章
文章詳情頁

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

瀏覽:29日期:2023-10-01 13:45:02
1. 定義對象方法

JS 中對象方法的定義方式是在對象上定義一個指向函數的屬性,當方法被調用的時候,方法內的 this 就會指向方法所屬的對象。

let obj = { array: [1, 2, 3], sum: () => {console.log(this === window); // truereturn this.array.reduce((result, item) => result + item); }};console.log(this === window); //trueobj.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, 2, 3], sum() {console.log(this === window); // falsereturn this.array.reduce((result, item) => result + item); }};console.log(this === window); //trueconsole.log(obj.sum());//62.定義原型方法

同樣的規則適用于原型方法(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 會禁止你這么做,如果你這么做了,它就會拋出異常。

比如下面的代碼就會報錯:

const 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不能使用箭頭函數的資料請關注好吧啦網其它相關文章!

標簽: JavaScript
相關文章:
国产综合久久一区二区三区