# 函数
# 函数定义
函数是:可以重复使用的代码块。
比如某位老师要给学生家长发消息的动作,就可以定义为函数。
// 发消息函数。
let sendMessage = function (phone, message) {
console.log(`发送消息:${phone} -> ${message}`)
}
let phoneList = ['150xxx', '138xxx'];
for (let phone of phoneList) {
sendMessage(phone, '距离高考还有 30 天');
}
# 抽象
刚刚的例子中中 发消息
是重复动作。
只要是重复的动作,必须封装为函数
。这就是抽象的过程,将来我们学到面向对象还要更加深刻的理解抽象。
# 函数的语法
函数是包裹在 {...}
花括号中的代码,前面使用关键词 function 来声明
function fn() {
}
let fn1 = function() {
}
函数名和变量名一样,可以随处调用。你每次调用该函数时,会执行函数内的代码。
js 中有个对象 Function
,所有的函数都是 Function
的实现。js 中的函数不但是“头等公民”,而且可以像变量一样使用,具有非常强大的抽象能力。
// 发消息函数。
let sendMessage = function (phone, message) {
console.log(`发送消息:${phone} -> ${message}`)
}
let phone = '150xxx';
let nearExamination = function(sendMessage) {
sendMessage(phone, '距离高考还有 29 天');
}
# 函数的返回值
有时,你的函数要产出一个计算结果。此时你可以通过函数的 return
关键字来实现。
let getTime = function () {
let time = [
new Date().getFullYear(),
new Date().getMonth() + 1,
]
return time.join('-')
}
let time = getTime(); // 2020-07, 接收到计算机构
# 函数的参数对象 arguments
刚刚 sendMessage
函数的括号中有两个单词 phone, message
这叫做函数的参数。这个参数没有个数限制。
如果你的函数想要接收任意参数,那么你需要使用 arguments
来遍历你的参数列表。这是函数的属性,是一个类数组的数据结构。
所以你也可以对 arguments
做遍历
function myFunction(param1, param2, param3) {
myFunction.arguments; // 这是函数的参数列表
console.log(myFunction.arguments)
myFunction.arguments[0] === param1; // true
myFunction.arguments[1] === param2; // true
for (let paramItem of arguments) {
console.log(paramItem);
}
}
# arguments.callee
arguments.callee 是指函数本身, 在某些情况下 callee 属性会非常有用。比如在匿名函数下实现递归
;(function(x) {
console.log(x);
x--;
if (x > 0) {
x = arguments.callee(x)
}
return x
})(5);
// 5
// 4
// 3
// 2
// 1