ES6標準新增了一種新的函數:Arrow Function(箭頭函數)。 為什麼叫Arrow Function?因為它的定義用的就是一個箭頭: 語法: 那麼箭頭函數有哪些特點? 更簡潔的語法 沒有this 不能使用new 構造函數 不綁定arguments,用rest參數...解決 使用call() ...
ES6標準新增了一種新的函數:Arrow Function(箭頭函數)。
為什麼叫Arrow Function?因為它的定義用的就是一個箭頭:
語法:
//1、沒有形參的時候 let fun = () => console.log('我是箭頭函數'); fun(); //2、只有一個形參的時候()可以省略 let fun2 = a => console.log(a); fun2('aaa'); //3、倆個及倆個以上的形參的時候 let fun3 = (x,y) =>console.log(x,y); //函數體只包含一個表達式則省略return 預設返回 fun3(24,44); //4、倆個形參以及函數體多條語句表達式 let fun4 = (x,y) => { console.log(x,y); return x+y; //必須加return才有返回值 }
//5、如果要返回對象時需要用小括弧包起來,因為大括弧被占用解釋為代碼塊了,正確寫法
let fun5 = ()=>({ foo: x }) //如果x => { foo: x } //則語法出錯
那麼箭頭函數有哪些特點?
- 更簡潔的語法
- 沒有this
- 不能使用new 構造函數
- 不綁定arguments,用rest參數...解決
- 使用call()和apply()調用
- 捕獲其所在上下文的 this 值,作為自己的 this 值
- 箭頭函數沒有原型屬性
- 不能簡單返回對象字面量
- 箭頭函數不能當做Generator函數,不能使用yield關鍵字
- 箭頭函數不能換行
相比普通函數更簡潔的語法
箭頭函數
var a = ()=>{ return 1; }
相當於普通函數
function a(){ return 1; }
沒有this
在箭頭函數出現之前,每個新定義的函數都有其自己的 this 值
var myObject = { value:1, getValue:function(){ console.log(this.value) }, double:function(){ return function(){ //this指向double函數內不存在的value console.log(this.value = this.value * 2); } } } /*希望value乘以2*/ myObject.double()(); //NaN myObject.getValue(); //1
使用箭頭函數
var myObject = { value:1, getValue:function(){ console.log(this.value) }, double:function(){ return ()=>{ console.log(this.value = this.value * 2); } } } /*希望value乘以2*/ myObject.double()(); //2 myObject.getValue(); //2
不能使用new
箭頭函數作為匿名函數,是不能作為構造函數的,不能使用new
var B = ()=>{ value:1; } var b = new B(); //TypeError: B is not a constructor
不綁定arguments,用rest參數...解決
/*常規函數使用arguments*/ function test1(a){ console.log(arguments); //1 } /*箭頭函數不能使用arguments*/ var test2 = (a)=>{console.log(arguments)} //ReferenceError: arguments is not defined /*箭頭函數使用reset參數...解決*/ let test3=(...a)=>{console.log(a[1])} //22 test1(1); test2(2); test3(33,22,44);
使用call()和apply()調用
由於 this 已經在詞法層面完成了綁定,通過 call() 或 apply() 方法調用一個函數時,只是傳入了參數而已,對 this 並沒有什麼影響:
var obj = { value:1, add:function(a){ var f = (v) => v + this.value; //a==v,3+1 return f(a); }, addThruCall:function(a){ var f = (v) => v + this.value; //此this指向obj.value var b = {value:2}; return f.call(b,a); //f函數並非指向b,只是傳入了a參數而已 } } console.log(obj.add(3)); //4 console.log(obj.addThruCall(4)); //5
捕獲其所在上下文的 this 值,作為自己的 this 值
var obj = { a: 10, b: function(){ console.log(this.a); //10 }, c: function() { return ()=>{ console.log(this.a); //10 } } } obj.b(); obj.c()();
箭頭函數沒有原型屬性
var a = ()=>{ return 1; } function b(){ return 2; } console.log(a.prototype);//undefined console.log(b.prototype);//object{...}
不能簡單返回對象字面量
如果要返回對象時需要用小括弧包起來,因為大括弧被占用解釋為代碼塊了,正確寫法
let fun5 = ()=>({ foo: x }) //如果x => { foo: x } //則語法出錯
箭頭函數不能當做Generator函數,不能使用yield關鍵字
箭頭函數不能換行
let a = () =>1; //SyntaxError: Unexpected token =>