Javascript 对象分解内部函数语法
在下面的代码中,我了解到对象解构使Javascript 对象分解内部函数语法,javascript,Javascript,在下面的代码中,我了解到对象解构使console.log(occulation)等同于console.log(luke.occulation) 但是,我不明白在不进行对象分解的情况下,下面的console.log(getState())等价物是什么,因为console.log(makeState.getState())没有意义 function makeState() { let state: number function getState() { return state
console.log(occulation)
等同于console.log(luke.occulation)
但是,我不明白在不进行对象分解的情况下,下面的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())
的等价物是什么?解构使occulation
等价于luke.occulation
。他们都返回“绝地”,直到
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'
因此,正如您所看到的,解构将解构属性的当前值复制到变量中,但仅此而已
这基本上是一种语法糖
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
…没有
\u temp
变量。const state=makeState()
,然后使用state.getState()
。解构仅仅是获取变量的属性makeState
返回一个具有getState
属性的对象。为什么const{getState,setState}=makeState()
要创建另一个名为state
的const
@ElijahLee这是有效的javascript,因此不需要任何编译。但是,如果您为IE支持传输它,babel default会像这样传输它:var\u makeState=makeState(),getState=\u makeState.getState,setState=\u makeState.setState代码>您可以在上测试它
const _temp = makeState()
const setState = _temp.setState
const getState = _temp.getState