在箭頭函數出現以前,每一個新定義的函數都有其本身的 this 值javascript
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賦給一個變量來解決:java
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() 函數。express
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 值,所以下面的代碼將如期運行。app
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();
因爲 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
var foo = (...args) => { return args[0] } console.log(foo(1)) //1
箭頭函數不能用做構造器,和 new 一塊兒用就會拋出錯誤。ui
var Foo = () => {}; var foo = new Foo(); //Foo is not a constructor
箭頭函數沒有原型屬性。this
var foo = () => {}; console.log(foo.prototype) //undefined
var func = () => { foo: 1 }; // Calling func() returns undefined! var func = () => { foo: function() {} }; // SyntaxError: function statement requires a name //若是要返回對象字面量,用括號包裹字面量 var func = () => ({ foo: 1 });
var obj = { value:1, add:() => console.log(this.value), double:function(){ console.log(this.value * 2) } } obj.add(); //undefined obj.double(); //2
var func = () => 1; // SyntaxError: expected expression, got '=>'