Spying on Properties

node v6.17.1
version: 1.0.0
endpointsharetweet
const DEFAULT_CALLBACK = (val, identifier) => console.log(`[${identifier}] Setting val: ${val}`); /** * Spies on a property of an object, gives the object a random identifier, and * calls an optional callback whenever the value is set. * * @param {any} on - The object to spy on * @param {string} prop - The name of the property to spy on */ function spy(on, prop, callback=DEFAULT_CALLBACK) { const rand = Math.random(); on.__rand = rand; Object.defineProperty(on, prop, { get: () => { return on[`__${prop}`]; }, set: (val) => { DEFAULT_CALLBACK(val, rand); on[`__${prop}`] = val; } }); }
const thing = { a: 'asdf' }; spy(thing, 'a'); thing.a = 1; thing.a = 2; thing.a = 'fdsa'; 0;
Loading…

no comments

    sign in to comment