什么時候不能使用箭頭函數?


什么時候不能使用箭頭函數?

1、定義對象方法

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

1.1定義字面量方法

	//1.定義字面量方法
	const calculator = {
		array:[1,2,3],
		sum: ()=>{
			console.log(this,window);
			return this.array.reduce((result, item) => result+item);
		}
	}
	console.log(this,window);
	calculator.sum()

 因為運行的時候this.array未定義,調用calculator.sum時,執行上下文里的this仍指向的是window,原因是箭頭函數把函數上下文綁定到了window上,this.array==window.array,后者又是未定義,所以會報錯。

 

解決辦法是使用普通函數,這樣可以確保this是在運行時由包含它的上下文決定的:

	const calculator = {
		array:[1,2,3],
		sum(){
			console.log(this,window);
			return this.array.reduce((result, item) => result+item);
		}
	}
	console.log(this,window);
	calculator.sum();

1.2 定義原型方法

定義原型方法時,使用箭頭函數會導致運行時的執行上下文錯誤

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

	const cat = new Dat('Kitty');
	cat.sayCatName();//undefined

  

	let Cat = function(name){
		this.name = name;
	}
	Cat.prototype.sayCatName = function(){
		console.log(this, window);
		return this.name;
	}

	const cat = new Cat('Kitty');
	cat.sayCatName();//undefined

1.3 定義事件回調函數

箭頭函數定義的上下文是不能改的,這樣執行的時候this就等同於window,這樣的話是沒有任何意義的

	var btn = document.getElementById('btn');
	btn.addEventListener('click',()=>{
		console.log(this, window);
		this.innerHTML = 'click btn';
	})

 

	btn.addEventListener('click',function(){
		console.log(this, window);
		this.innerHTML = 'click btn';
	})

1.4 定義構造函數

	const Book = (name)=>{
		this.name = name;
	}

	const book = new Book('John');
	console.log(book.name);//arrow.html:75 Uncaught TypeError: Book is not a constructor

  

	const Book = function(name){
		this.name = name;
	}

	const book = new Book('John');
	console.log(book.name);

1.5 追求過短的代碼

刻意追求過短的代碼,可能會給代碼閱讀和邏輯理解帶來困難。

const multiply = (a, b) => b === undefined ? b => a * b : a * b;
const double = multiply(2);
double(3);      // => 6
multiply(2, 3); // => 6

  

function multiply(a, b) {
    if (b === undefined) {
        return function (b) {
            return a * b;
        }
    }
    return a * b;
}

const double = multiply(2);
double(3); // => 6
multiply(2, 3); // => 6

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM