es6 的 function
var fn = () => 'Hello';
即為
function fn () {
return 'Hello';
}
如果只帶一個參數,可以拿掉parentheses(),如下
var fn = a => a+5;
this 指向
es5
function doSth(){
console.log(this)
}
1.直接console.log function,結果是印出window物件
console.log(doSth()) // [object Window] { ... }
2.直接在HTML的body內添加button tag,接著加上下面這行程式,結果是印出呼叫此function的物件→即object HTMLButtonElement
button.addEvenetListener('click', fn)// [object HTMLButtonElement] { ... }
結論:this always refers to 呼叫此function的物件
es6
var fn2 = () => console.log(this);
button .addEventListener('click',fn2); // [object Window] { ... }
結論:this always refers to what it refers when you define the function no matter how or where you call the function
沒有留言:
張貼留言