简体   繁体   中英

Is it possible to define a 'global' getter/setter method on a Javascript object, so that it is invoked whenever any property is got/set?

Let's say we have an Object:

const obj = {
  foo: bar,
  boop: "beep",
}

Now I would like to add some functionality that occurs any time a property is set (also get for this matter actually) in this object. Let's just keep it simple and say the added functionality is just a console.log("a set/get action was just triggered on obj!") .

How can I achieve this?

Advanced extension:

Naming the the property that was set and the value it was set with.

some sample behavior for clarity:

// simple:
obj.foo = "not bar anymore!";
// console output: a set/get action was just triggered on obj!

obj.rand = "a randomly added prop here";
// console output: a set/get action was just triggered on obj!


// advanced:
obj.boop = "burp";
// console output: a set/get action was just trigged on obj with prop: "boop", value: "burp".
obj.newRand = "a new randomly added prop here";
// console output: a set/get action was just trigged on obj with prop: "newRand", value: "a new randomly added prop here";

Bonus:

Any other ways to solve this issue are welcome.

Use a Proxy object with getter/setter traps instead.

The traps in the Proxy object allow you to interject the object methods with your custom functionality while returning the actual object data in the end of the process.

Code example:

 const obj = { foo: 'bar', boop: "beep", }; const objProx = new Proxy(obj, { get(obj, prop) { console.log('On obj', obj, 'getting', prop); return obj[prop]; }, set(obj, prop, newVal) { console.log('On obj', obj, 'setting', prop, 'to', newVal); return obj[prop] = newVal; }, }); objProx.boop = "burp"; objProx.newRand = "a new randomly added prop here"; // invokes getter: objProx.foo; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM