雖然匿名函式很好用,但有時在許多callback時會造成難以閱讀
setTimeout(function(){
console.log("hello world")
}, 3000);
具名函式有名稱會比較好閱讀,雖說匿名與具名沒有差別,但對於readability很有幫助
setTimeout(function Hello(){
console.log("hello world")
}, 3000);
箭頭函式提供更簡潔的寫法,但要注意Arrow function會指定this
a = 1
const func = () =>{
console.log(this.a) //undefined
}
func()
function hello(){
console.log(this.a) //1 RHS全域的a
}
hello()
function(a){
console.log("Start")
for(let i = 0; i < a ; i++){
console.log(i)
}
console.log("end-for")
}
(function(a){
console.log("Start")
for(let i = 0; i < a ; i++){
console.log(i)
}
console.log("end-for")
})(5) //Start 1,2,3,4,5 end-for
var name = "Dennis";
(function(){
var name = "Jessica";
console.log(name); //Jessica
})()
console.log(name); //Dennis