es6新增箭頭函數,主要解決了如下幾點問題es6
var obj = {
a:
1,
b:
2,
c:
function(){
setTimeout(
()=>{
console.log(this);
},
1000)
},
d:
function(){
setTimeout(
function(){
console.log(this)
},
1000)
}
}
obj.c();
//obj
obj.d();
//window
|
setTimeout的this爲window,因此d()會輸出window,而使用箭頭函數則會輸出obj函數
var obj = {
a:
function(){
console.log(this)
},
b:
()=>{
console.log(this);
}
}
obj.a()
//obj
obj.b()
//window
|
可見箭頭函數裏面的this是離他最近的做用域鏈的thisui
var x = new obj.a();
var y = new obj.b();//報錯
|
可見箭頭函數不能使用new命令。this
var obj = {
a:
function(){
console.log(arguments)
},
b:
()=>{
console.log(arguments);
}
}
obj.a()
obj.b()
//arguments is not defined
|
沒有arguments。spa