-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdestructuring.js
86 lines (80 loc) · 1.7 KB
/
destructuring.js
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* https://tc39.es/ecma262/#sec-destructuring-binding-patterns
* 递归解构绑定符号
*
* BindingPattern:
* ObjectBindingPattern
* ArrayBindingPattern
*
* ArrayBindingPattern:
* ...BindingRestElement
* BindingElementList
* BindingElementList , ...BindingRestElement
*
* BindingElement:
* SingleNameBinding
* BindingPattern Initializer(opt)
*
* SingleNameBinding:
* BindingIdentifier Initialize(opt)
*
* BindingIdentifier
* Identifier
*
* babel 会自动转义成逐个变量赋值
*/
var [a, , b] = [1, 2, 3];
a === 1;
b === 3;
/**
* ObjectBindingPattern:
* {}
* BindingRestProperty
* BindingPropertyList
* BindingPropertyList , BindingRestProperty
*
* BindingRestProperty : ... BindingIdentifier
*
* BindingPropertyList
* BindingProperty
* BindingPropertyList BindingProperty
*
* BindingProperty
* SingleNameBinding
* PropertyName : BindingElement
*
* PropertyName
* LiteralPropertyName
* ComputedPropertyName
*
* LiteralPropertyName
* IdentifierName
* StringLiteral
* NumericLiteral
*
* ComputedPropertyName
* AssignmentExpression
*
* babel 解析给指定变量赋值 b = _getASTNode.lhs.op,
*/
var { op: a, lhs: { op: b }, rhs: c }
= getASTNode()
// 对象匹配的简写
// 在作用域中绑定 `op`, `lhs` and `rhs`
var { op, lhs, rhs } = getASTNode()
// 可用于参数位置
function g({ name: x }) {
console.log(x);
}
g({ name: 5 })
// 解构失败
var [a] = [];
a === undefined;
// 解构失败时使用默认值
var [a = 1] = [];
a === 1;
// 解构 + 默认参数,见上面的对象解构
function r({ x, y, w = 10, h = 10 }) {
return x + y + w + h;
}
r({ x: 1, y: 2 }) === 23