Getters in ES6 are usually defined within a class like this:
1 2 3 4 5 6 7 8 | class RandomPoint { get x() { return Math.random(); } get y() { return Math.random(); } } |
In this case we use getters to make a random point:
let pnt = new RandomPoint(); console.log(pnt.x, pnt.y); // outputs something like 0.09403673512366306 0.2717692041118973
I found myself wanting to be able to dynamically define a getter. This can be done like this:
let rand = function() { return Math.random(); }; Object.defineProperties(someObj, { ['x']: { get: rand });
This is really all just sugar, but still fun stuff…