Reputation: 2957
In the code below, I understand that object destructuring makes console.log(occupation)
equivalent to console.log(luke.occupation)
let luke = { occupation: 'jedi', father: 'anakin' };
let {occupation, father} = luke;
console.log(occupation); // 'jedi'
console.log(father); // 'anakin'
However I do not understand what the equivalent to console.log(getState())
is below without object destructuring as console.log(makeState.getState())
does not make sense.
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
What is the equivalent of console.log(getState())
without using the object destructuring syntax?
Upvotes: 0
Views: 38
Reputation: 18619
You're wrong in the part that destructuring makes occupation
equivalent to luke.occupation
. They both return 'jedi'
, until...
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'
So, as you can see, destructuring copies the current value of the destructured property into the variable, but nothing more than that.
It's basically syntactic sugar for
let occupation = luke.occupation
let father = luke.father
In your second case, the same happens.
The setState
and getState
properties of an object returned by makeState
get assigned to the setState
and getState
variables.
The magic that they point to the same state, is in the functions themselves: they both receive a closure scope from their parent, makeState
, and as they are from the same call to makeState
, they access the same closure.
So, to answer your question anyway, you can think of this code like...
const _temp = makeState()
const setState = _temp.setState
const getState = _temp.getState
...without having a _temp
variable.
Upvotes: 1