Object.defineProperty() API
by harps116
HTML
<!-- logging outside the console -->
<pre><script>
function log(arg){
document.writeln(arg);
document.write('<br/>')
}
</script></pre>
JavaScript
// this will convert our state object into an object that now has accessors
function convert (obj) {
Object.keys(obj).forEach(key => {
let internalValue = obj[key]
Object.defineProperty(obj, key, {
get () {
log(`getting key "${key}": ${internalValue}`)
return internalValue
},
set (newValue) {
log(`setting key "${key}" to: ${newValue}`)
internalValue = newValue
}
})
})
}
let guineaPig = {
a : '',
}
convert(guineaPig);
console.log(guineaPig); // open up the console to see the getters and setters `ctrl + shift + i`
// see result -->
guineaPig.a
guineaPig.a = 'testing'
guineaPig.a