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

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. });

Pretty Print JSON in Console

  1.   const obj = {
  2.     x: 1, y: 2,
  3.     data: { test: 'xyz' }
  4.   };
  5.   console.log(JSON.stringify(obj, null, 2));

JSON.stringify has two more arguments that allow for pretty printing and processing of the object in question. The second argument is a “replacer” function and the third argument is for indentation. Read more details here.

I am pretty sure I first learned this from this stack overflow post.

I used this technique in yesterdays console hijacking post.

snippet.zone ~ 2021-24 /// {s/z}