標籤:fine UNC ofo ssi oba 調用 http argument stat
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乘以2myObject.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()(); //2myObject.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()(); //2myObject.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)); //2console.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(); //undefinedobj.double(); //2
8.箭頭函數不能換行
var func = () => 1; // SyntaxError: expected expression, got ‘=>‘
箭頭函數和普通函數的區別