"Proxy" is a frequently used pattern in both virtual world and real world. Those patterns("proxy", "iterator" and "observer",etc) make coding more personably, as if we're building lots of maganificent skyscrapers with robust methods and tools.
// Create an observer to detect the opening state of light
const basicState = {
open: false
}
const lightState = new Proxy(basicState, {
set(obj, prop, value) {
if (prop === 'open') {
switch(value) {
case true:
console.log('Light on!')
break
case false:
console.log('Light off!')
}
}
return true
}
})
// Turn on light
lightState.open = true // output: Light on!
// Turn off light
lightState.open = false // output: Light off!
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
Try Proxy? Trust it at first
Thanks for your reading. Welcome to subscribe my blog by Github.