mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 18:32:22 +00:00
docs(object): 修改扩展运算符自动执行取值函数 get 的例子
This commit is contained in:
parent
491f6f04cf
commit
cd0310c978
@ -693,25 +693,17 @@ const obj = {
|
|||||||
扩展运算符的参数对象之中,如果有取值函数`get`,这个函数是会执行的。
|
扩展运算符的参数对象之中,如果有取值函数`get`,这个函数是会执行的。
|
||||||
|
|
||||||
```javascript
|
```javascript
|
||||||
// 并不会抛出错误,因为 x 属性只是被定义,但没执行
|
let a = {
|
||||||
let aWithXGetter = {
|
|
||||||
...a,
|
|
||||||
get x() {
|
get x() {
|
||||||
throw new Error('not throw yet');
|
throw new Error('not throw yet');
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
// 会抛出错误,因为 x 属性被执行了
|
let aWithXGetter = { ...a }; // 报错
|
||||||
let runtimeError = {
|
|
||||||
...a,
|
|
||||||
...{
|
|
||||||
get x() {
|
|
||||||
throw new Error('throw now');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
上面例子中,取值函数`get`在扩展`a`对象时会自动执行,导致报错。
|
||||||
|
|
||||||
## 链判断运算符
|
## 链判断运算符
|
||||||
|
|
||||||
编程实务中,如果读取对象内部的某个属性,往往需要判断一下该对象是否存在。比如,要读取`message.body.user.firstName`,安全的写法是写成下面这样。
|
编程实务中,如果读取对象内部的某个属性,往往需要判断一下该对象是否存在。比如,要读取`message.body.user.firstName`,安全的写法是写成下面这样。
|
||||||
|
Loading…
x
Reference in New Issue
Block a user