园长

学无止境 知行合一

闭包

条件

  • 嵌套的函数
  • 内部函数要引用外部函数

理解

  • 访问到外部函数作用域中的变量
  • 延长局部变量的生命周期
  • 应用:JS模块

生命周期

  • 产生:在嵌套内部函数的定义执行时产生

  • 死亡:内部函数成为垃圾对象时销毁

常见闭包

函数作为另一函数的返回值

1
2
3
4
5
6
7
8
9
10
11
function fn(){
let a = 1 // 闭包产生(函数提升)
function fn2(a){
a++
console.log(a)
}
return fn2
}

let test = fn()
test = null // 闭包死亡

函数作为实参

1
2
3
4
5
6
7
function show(a,time){
setTimeout(function(){
console.log(a)
},time)
}

show("hahaha", 1000)

JSON

  • JSON.stringify()
  • JSON.parse()

事件

  • event.target 触发事件的对象
  • event.currentTarget 绑定事件的对象, 同this
  • event.stopPropagation() 停止事件的传播
  • event.preventDefault() 取消默认行为

事件传播

时间的传播机制

  1. 捕获阶段 (由外向内捕获)
  2. 目标阶段
  3. 冒泡阶段 (由内向外冒泡)
  • event.eventPhase 事件的阶段

    返回1, 2, 3

addEventListener 的第三个参数设置为 true

面向对象

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Test{
#a = "a"
static b = "b"
#foo

constructor(foo){
this.foo = foo
}

say(){
console.log(this.foo)
}

static fn(){
console.log("fn")
}

set a(a){
this.#a = a
}

get a(){
return this.#a
}
}


class T extends Test{

constructor(foo, foo2){
super(foo)
this.foo2 = foo2
}
say(){
super.say() // 可调用父类的 say()
console.log("T")
}
}

let a = new T()
console.log(a.a) // "a"
console.log(a.b) // undefind
console.log(a.foo) // undefind
console.log(T.b) // "b"

TypeScript

当在学习 JS 过程中,我在想 JS 中怎样进行 Python 中的如下操作:

1
2
def fun(a: int, b:str) -> str:
return str(a) + b

也就是类型注解,嗷,看课过程中隐隐觉得 TS 应该是干这个的,原来真是



 评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 volantis 作为主题 。