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