Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 208
UICodes Avatar asked May 05 '10 17:05

UICodes


People also ask

How do you check if an object has a specific property?

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.

How do you check if an object has a specific property in JavaScript?

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).

Can a property be added to an existing object in JavaScript?

You can add new properties to an existing object by simply giving it a value.

Should I use hasOwnProperty?

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() .


1 Answers

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?

like image 130
bobince Avatar answered Sep 28 '22 21:09

bobince