# 函数
函数声明
function fn() {}
1
函数表达式
var fn = function() {}
1
什么是回调函数
已经定义
没有调用
但最终它执行了(在某个时刻和某个条件下)
有哪些回调函数
- dom事件回调函数 ==> 发生事件的dom元素
- 定时器回调函数 ==> window
- ajax亲求回调函数
- 生命周期回调函数
# IIFE(立即执行函数表达式)
# 作用
- 隐藏内部实现
- 不会污染全局命名空间
- 编写js模块
;(function() {
var a = 3
console.log(a + 3)
})()
1
2
3
4
2
3
4
;(function() {
var a = 1
function test() {
console.log(++a)
}
window.$ = function() {
return {
test: test
}
}
})()
$().test()
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 函数中的this
this 是什么
任何函数本质上都是通过某个对象调用的
所有函数内部都有一个变量 this
它的值是调用函数的当前对象
如何确顶 this 的值
- test(): window
- p.test(): p
- new test(): 新创建的对象
- p.call(obj): obj
function Person() {
console.log(this)
this.color = function() {
console.log(this)
}
this.setColor = function() {
console.log(this)
}
}
Person() // this 指向 window
var p = new Person() // this 指向 p
p.color() // this 指向 p
var obj = {}
p.setColor.call(obj) // this 指向 obj
var test = p.setColor;
test() // this 指向 window
function fun1() {
function fun2() {
console.log(this)
}
fun2() // this 指向 window
}
fun1()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28