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
The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.
Object.prototype.hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
You can add new properties to an existing object by simply giving it a value.
In general, hasOwnProperty() is the right choice most of the time, because you avoid issues with special keys, like constructor . A good rule of thumb is that if you're looking to see whether an object has a property, you should use hasOwnProperty() .
Nope. The existing methods of determining when a property gets written to:
defineProperty(obj, name, fn)
;__defineSetter__(name, fn)
;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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With