Could use some feedback on a Saturday afternoon object composition/closure investigation (is it accurate, is it missing any key points, non-key points, can you help answer remaining questions/provide resources to do so). Thanks in advance :)
run here: https://www.typescriptlang.org/play#code/ or in some typescript debug env or remove all typings and run in node
interface Inner {
(closureScopedInput?: string): string
}
function outer(input: string): Inner {
debugger
console.log('input:', input);
return function(closureScopedInput: string | undefined) {
debugger
console.log('closureScopedInput changing:', closureScopedInput);
return `output = ${input} ${closureScopedInput}`
}
}
const setClosureScope = outer('1')
console.log('example1:', setClosureScope('2'))
console.log('example2:', setClosureScope('3'))
console.log('example3:', setClosureScope('4'))
console.log('example4:', setClosureScope('5'))
questions:
- why is the first
debugger/console.log('input:', input)
hit only whenouter
is expressed assetClosureScope
, and not on every subsequentsetClosureScope
call when new values are passed in? - how does this memory storage actually work with regards to scoped execution context and memory references?
conclusions:
when the function outer
is expressed as variable setClosureScope
:
- the value passed into the outer function is stored in memory as a closure scope
- This technique/methodology of wrapping data in closures is: - common in object composition - powerful because it locks data down to the scope of nested closures inside objects that encapsulate these data properties as members