简体   繁体   中英

Detect when a new property is added to a Javascript object?

A simple example using a built-in javascript object: navigator.my_new_property = "some value"; //can we detect that this new property was added?

I don't want to constantly poll the object to check for new properties. Is there some type of higher level setter for objects instead of explicitly stating the property to monitor?

Again, I don't want to detect if the property value changed, but rather when a new property is added.

Ideas? thanks

Nope. The existing methods of determining when a property gets written to:

  • an ECMAScript 5 setter defined using defineProperty(obj, name, fn) ;
  • a legacy JavaScript setter defined using __defineSetter__(name, fn) ;
  • a legacy Netscape/Mozilla watch(name, fn) ;

are all name-based, so can't catch a new property being written with a previously-unknown name. In any case, navigator may be a 'host object', so you can't rely on any of the normal JavaScript Object interfaces being available on it.

Polling, or explicit setter methods that provide callback, is about all you can do.

Similar situation: Getter/setter on javascript array?

ES6 introduces the concept of Proxies: es6 proxies on MDN .

Here is a simple example:

let objectToSpy = {};
let handler = {
    set: (target, prop, value)=>{
        console.log('new prop:', prop);
        target[prop] = value;
    }
};

let proxy = new Proxy(objectToSpy,handler);
proxy.testProp = 'bla'; //prints: "new prop: testProp"

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