在下面的代码中,我理解对象析构函数使console.log(occupation)
等价于console.log(luke.occupation)
let luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;
console.log(occupation); // 'jedi'
console.log(father); // 'anakin'
然而,我不明白在没有对象破坏的情况下,console.log(getState())
的等价物是什么,因为console.log(makeState.getState())
没有意义。
function makeState() {
let state: number
function getState() {
return state
}
function setState(x: number) {
state = x
}
return { getState, setState }
}
const { getState, setState } = makeState()
setState(1)
console.log(getState()) // 1
setState(2)
console.log(getState()) // 2
在不使用对象析构函数语法的情况下,console.log(getState())
的等价物是什么?
您错误地认为析构函数使occupation
等效于luke.occupation
。他们都返回'jedi'
,直到。。。
let luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;
console.log(occupation); // 'jedi'
luke.occupation = 'noLongerJedi'
console.log(occupation); // 'jedi'
console.log(luke.occupation); // 'noLongerJedi'
因此,正如您所看到的,destructuring将destructured属性的当前值复制到变量中,但仅此而已。
这基本上是的句法糖
let occupation = luke.occupation
let father = luke.father
在第二种情况下,也会发生同样的情况。
由makeState
返回的对象的setState
和getState
属性被分配给setState
和getState
变量。
它们指向相同状态的神奇之处在于函数本身:它们都从父级makeState
接收闭包作用域,并且由于它们来自对makeState
的同一调用,因此它们访问相同的闭包。
所以,无论如何,要回答你的问题,你可以把这个代码想象成。。。
const _temp = makeState()
const setState = _temp.setState
const getState = _temp.getState
而不具有CCD_ 16变量。