1. 程式人生 > 實用技巧 >18.箭頭函式與普通函式有什麼區別

18.箭頭函式與普通函式有什麼區別

目錄

正文

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 =>