箭頭函數和普通函數的區別


js箭頭函數和普通函數的區別

1.不邦定this

在箭頭函數出現之前,每個新定義的函數都有其自己的 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 函數,把期望的 this 值傳遞給 double() 函數。

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 

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

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

2.使用call()和apply()調用

由於 this 已經在詞法層面完成了綁定,通過 call() 或 apply() 方法調用一個函數時,只是傳入了參數而已,對 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.箭頭函數不綁定arguments,取而代之用rest參數…解決

var foo = (...args) => { return args[0] } console.log(foo(1)) //1 

4.使用new操作符

箭頭函數不能用作構造器,和 new 一起用就會拋出錯誤。

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

5.使用原型屬性

箭頭函數沒有原型屬性。

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.箭頭函數當方法使用的時候沒有定義this綁定

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

8.箭頭函數不能換行

var func = () => 1; // SyntaxError: expected expression, got '=>'


免責聲明!

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



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