箭頭函數與普通function的區別


1. 箭頭函數沒有自己的this,它里面的this是繼承所屬上下文中的this,而且使用call與apply都無法改變
	let obj = {
		name: 'obj'
	}
	function fn1() {
		console.log(this);
	}
	
	fn1.call(obj);
	
	let fn2() => {
		console.log(this);
	}
	fn2.call(obj);
2. 普通函數的參數是arguments,而箭頭函數是arg
	let arr = [1,2,3]
	~function(){
		console.log(arguments);
	}
	(arr); //輸出 [1,2,3]
	let a = (...arg) => {
		console.log(arg);
	}
	a(arr) //輸出[1,2,3]
3. 語法上比普通函數更加簡潔
	function fn1(x) {
		return function(y) {
			return x + y;
		}
	}
	
	let fn1 = x => y => x + y;
4. 箭頭函數不能使用new生成構造函數,因為箭頭函數沒有prototype,而construct在prototype里面。
	function Fn1() {
		this.x = 100;
	}
	let f1 = new Fn1;
	
	let Fn2 = () => {
		this.x = 200;
	}
	
	let f2 = new Fn2; //輸出 Fn2 is not a constructor
	


免責聲明!

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



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