Add Getter Setter to Object
const target = {}
let value = null;
Object.defineProperties(target, {
magic: {
get() {
console.log('- getter called::', value);
return value;
},
set(val) {
document.body.innerHTML += val + '<br>';
value = val;
}
}
});
target.magic = 'xyz';
target.magic = 'snippet';
target.magic = 'zone';
target.magic = '- last value';
console.log('getting', target.magic);
This snippet shows a way to add getters and setters to a specific key of an existing object. This is powerful for decorating configuration objects with special behaviors. This kind of thing can easily be created with a little more abstraction:
const image = view({
tag: 'img',
src: 'myImage.jpg',
x: '20%',
y: '20%',
size: '50%'
});
const prev = view({
tag: 'button',
x: () => image.x,
y: () => image.bottom
});
const next = view({
tag: 'button',
x: () => image.right - this.width,
y: () => image.bottom
});