)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Add Getter Setter to Object

  1. const target = {}
  2.  
  3. let value = null;
  4. Object.defineProperties(target, {
  5.   magic: {
  6.     get() {
  7.       console.log('- getter called::', value);
  8.       return value;
  9.     },
  10.     set(val) {
  11.       document.body.innerHTML += val + '<br>';
  12.       value = val;
  13.     }
  14.   }
  15. });
  16.  
  17. target.magic = 'xyz';
  18. target.magic = 'snippet';
  19. target.magic = 'zone';
  20. target.magic = '- last value';
  21.  
  22. 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:

  1. const image = view({
  2.   tag: 'img', 
  3.   src: 'myImage.jpg',
  4.   x: '20%', 
  5.   y: '20%',
  6.   size: '50%'
  7. });
  8. const prev = view({
  9.   tag: 'button',
  10.   x: () => image.x,
  11.   y: () => image.bottom
  12. });
  13. const next = view({
  14.   tag: 'button',
  15.   x: () => image.right - this.width,
  16.   y: () => image.bottom
  17. });
snippet.zone ~ 2021-24 /// {s/z}