函数长啥样?
把一些要重复使用的内容封装到函数内。
function foo(title) {
console.log(title)
}
foo('title')
foo('dust')
foo('hello')
运行结果:
用对象把函数装起来
let user = {
name: null,
setUsername: function (name) {
this.name = name
},
getUsername: function () {
return this.name
},
}
user.setUsername('dust')
console.log(user.getUsername())
运行结果:
简写的形式:
let user = {
name: null,
setUsername(name) {
this.name = name
},
getUsername() {
return this.name
},
}
匿名函数与函数提升
- 没名字的函数:匿名函数
- 匿名函数是不会提升的,在函数前执行是不行的~
let foo = function () {
console.log('hello')
}
- 有名字的函数:具名函数
- 虽然程序是从上到下解析的,但是它函数提升啦!
- 变量提升:你把它想象在全文最上方就好。
- 所以可以正常执行
show()
function show() {
console.log('show')
}
运行结果:
箭头函数
function sum(...args) {
return args.reduce((a, b) => {
return a + b
})
}
console.log(sum(1, 2, 3, 4, 5))
运行结果:
形参和实参
function sum(a, b, c) {
//这里是形参
console.log(c)
return a + b
}
console.log(sum(1, 2)) //这里是实参
运行结果:
- 当实参多了的时候,会被忽略。
- 当形参多了的时候,会被定义但未赋值,所以是undefined
默认参数
- 解决实参缺少的问题
function sum2(a, b = 1) {
return a + b
}
console.log(sum2(1))
运行结果:
函数作为参数
- 以setInterval为例
let i = 0
setInterval(() => {
console.log(++i)
}, 1000)
功能:每秒输出+1的数
运行结果:
Arguments的使用
- 在js中,传入的参数可以在Arguments中看见(这点非常有意思喔)
function getSum(...args) {
console.log(arguments)
return args.reduce((a, b) => a + b)
}
console.log(getSum(1, 2, 3, 4, 5))
运行结果:
回调函数
- test.html
- 回调函数在DOM操作里的体现
- 回调函数是一个函数在参数里,就是在其他函数里又调用了一个函数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<button id="bt">hello</button>
</body>
<script>
document.getElementById('bt').addEventListener('click', function () {
alert(this.innerHTML)
})
</script>
</html>
this指针的改变
在map()里通过传入this以改变this的指向
不传入this的情况:
let Lesson = {
site: 'hd',
lists: ['js', 'css', 'mysql'],
show: function () {
return this.lists.map(function (value) {
return `${this.site}-${value}`
})
},
}
console.log(Lesson.show())
运行结果:
由于没有传入外部的this,在lists里没有site这个属性,所以是undefined
如果我们传入this:
let Lesson = {
site: 'hd',
lists: ['js', 'css', 'mysql'],
show: function () {
return this.lists.map(function (value) {
return `${this.site}-${value}`
}, this)
},
}
console.log(Lesson.show())
运行结果:
就成功将this指针指向了Lesson里的内容。