一、什么是函数
- 实现特定功能的n条语句的封装体
- 只有函数是可以执行的, 其它类型的数据不能执行
function showInfo (age) {
if(age<18) {
console.log('我未成年')
} else if(age>60) {
console.log('我老了')
} else {
console.log('我要努力工作')
}
}
showInfo(17)
showInfo(20)
showInfo(65)
二、为什么要用函数
- 提高代码复用
- 便于阅读交流
三、如何定义函数
- 函数声明
- 表达式
function fn1 () { //函数声明
console.log('fn1()')
}
var fn2 = function () { //表达式
console.log('fn2()')
}
fn1()
fn2()
四、如何调用(执行)函数
- test():直接调用
- obj.test():通过对象调用
- new test():new调用
- test.call/apply(obj):临时让test成为obj的方法进行调用
var obj = {}
function test2 () {
this.xxx = 'xxxxx'
}
// obj.test2() 不能直接, 根本就没有
test2.call(obj) // 相当于 obj.test2() // 可以让一个函数成为指定任意对象的方法进行调用
console.log(obj.xxx)
五、什么函数才是回调函数
1). 你定义的
2). 你没有调
3). 但最终它执行了(在某个时刻或某个条件下)
document.getElementById('btn').onclick = function () { // dom事件回调函数
alert(this.innerHTML)
}
setTimeout(function () { // 定时器回调函数
alert('到点了')
}, 2000)
六、常见的回调函数
- dom事件回调函数 —>发生事件的dom元素
- 定时器回调函数 —>window
- ajax请求回调函数
- 生命周期回调函数
七、IIFE
- 理解
- 全称: Immediately-Invoked Function Expression 立即调用函数表达式
- 别名: 匿名函数自调用
- 作用
- 隐藏实现
- 不会污染外部命名(全局)空间
- 用它来编码js模块
(function () { //匿名函数自调用
var a = 3
console.log(a + 3) //6
})()
var a = 4
console.log(a) //4
;(function () {
var a = 1
function test () {
console.log(++a) //2
}
window.$ = function () { // 向外暴露一个全局函数
return {
test: test
}
}
})()
// 1. $是一个函数
//2. $执行后返回的是一个对象
$().test()
八、this是什么
- 任何函数本质上都是通过某个对象来调用的,如果没有直接指定就是window
- 所有函数内部都有一个变量this
- 它的值是调用函数的当前对象
- 在定义函数时,this还没有确定, 只有在执行时才动态确定(绑定)的
function Person(color) {
console.log(this)
this.color = color;
this.getColor = function () {
console.log(this)
return this.color;
};
this.setColor = function (color) {
console.log(this)
this.color = color;
};
}
Person("red"); //this是谁? window
var p = new Person("yello"); //this是谁? Person
p.getColor(); //this是谁? Person
var obj = {};
p.setColor.call(obj, "black"); //this是谁? obj
var test = p.setColor;
test(); //this是谁? window
function fun1() {
function fun2() {
console.log(this); //this是谁? window
}
fun2();
}
fun1();
九、如何确定this的值
- test():window
- p.test():p
- new test():新创建的对象
- p.call(obj):obj