###### tags: `ALPHACampWeek1`
函式操作
===
把函式放進變數
---
- function greet(name) { => 提升 (hoisting)
return `Hi, ${name}`
}
但我們也可以把函式當成值,放進變數:
const greet = function (name) {
return `Hi, ${name}`
}
當成物件屬性
---
const user = {
name: ['Peter', 'Lee'],
gender: 'Male',
age: 41,
greet: function () {
console.log(`Hello! I am ${this.name[0]}.`)
},
run: function () { console.log('run!')},
}
user.greet() // Hello! I am Peter.
當成另一個函式的回傳值
---
- 函式也可以當成另一個函式的回傳值
function game () {
console.log("Let's play game!")
return "I am happy!"
}
function breakfast () {
console.log(`I finished my breakfast.`)
return game() //把呼叫的函式回傳值當作自己的回傳值
}
const today = breakfast()
console.log(today)
當成另一個函式的參數
---
- I finished my breakfast -> Let's go to school. -> I am tired.
function game () {
console.log("Let's play game!")
return 'I am happy!'
}
//增加這個函式
function study(){
console.log("Let's go to school.")
return 'I am tired.'
}
//修改這個函式
function breakfast (callback) {
console.log(`I finished my breakfast.`)
return callback()
}
//呼叫時才決定吃完早餐要去讀書
const today = breakfast(study)
console.log(today)
匿名函式
---
- 直接使用匿名函式當參數
function game () {
console.log("Let's play game!")
return 'I am happy!'
}
// 註解起來
// function study(){
// console.log("Let's go to school.")
// return 'I am tired.'
// }
function breakfast (callback) {
console.log(`I finished my breakfast.`)
return callback()
}
//直接把匿名函式傳入,效果相同
const today = breakfast(function (){
console.log("Let's go to school.")
return 'I am tired.'
})
console.log(today)