js箭頭函數(shù)和普通函數(shù)的區(qū)別

1.不邦定this

在箭頭函數(shù)出現(xiàn)之前,每個新定義的函數(shù)都有其自己的 this

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  //希望value乘以2
myObject.getValue();  //1

在ECMAscript5中將this賦給一個變量來解決:

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    var that = this;
    return function(){
      console.log(that.value = that.value * 2); 
    }
  }
}

myObject.double()();  //2
myObject.getValue();  //2

除此之外,還可以使用 bind 函數(shù),把期望的 this 值傳遞給 double() 函數(shù)。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    return function(){
      console.log(this.value = this.value * 2); 
    }.bind(this)
  }
}

myObject.double()();  //2
myObject.getValue();  //2

箭頭函數(shù)會捕獲其所在上下文的 this 值,作為自己的 this 值,因此下面的代碼將如期運行。

var myObject = {
  value:1,
  getValue:function(){
    console.log(this.value)
  },
  double:function(){
    //回調(diào)里面的 `this` 變量就指向了期望的那個對象了
    return ()=>{
      console.log(this.value = this.value * 2); 
    }
  }
}

myObject.double()();  
myObject.getValue();  

2.使用call()和apply()調(diào)用

由于 this 已經(jīng)在詞法層面完成了綁定,通過 call() 或 apply() 方法調(diào)用一個函數(shù)時,只是傳入了參數(shù)而已,對 this 并沒有什么影響:

 var myObject = {
  value:1,
  add:function(a){
    var f = (v) => v + this.value;
    return f(a);
  },
  addThruCall:function(a){
    var f = (v) => v + this.value;
    var b = {value:2};
    return f.call(b,a);
    
  }
}

console.log(myObject.add(1));    //2
console.log(myObject.addThruCall(1));    //2

3.箭頭函數(shù)不綁定arguments,取而代之用rest參數(shù)…解決

var foo = (...args) => {
  return args[0]
}

console.log(foo(1))    //1

4.使用new操作符

箭頭函數(shù)不能用作構(gòu)造器,和 new 一起用就會拋出錯誤。

var Foo = () => {};
var foo = new Foo();  //Foo is not a constructor

5.使用原型屬性

箭頭函數(shù)沒有原型屬性。

var foo = () => {};
console.log(foo.prototype) //undefined

6.不能簡單返回對象字面量

var func = () => {  foo: 1  };
// Calling func() returns undefined!
var func = () => {  foo: function() {}  };
// SyntaxError: function statement requires a name
//如果要返回對象字面量,用括號包裹字面量
var func = () => ({ foo: 1 });

7.箭頭函數(shù)當方法使用的時候沒有定義this綁定

var obj = {
  value:1,
  add:() => console.log(this.value),
  double:function(){
    console.log(this.value * 2)
  }
}

obj.add();  //undefined
obj.double(); //2

8.箭頭函數(shù)不能換行

var func = ()
           => 1; // SyntaxError: expected expression, got '=>'
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容