Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way of assigning to __proto__ property

I have some objects deserialized from JSON to which I'd like to assign a new prototype in order to provide various getter and setter functions. The obvious way to do this (as mentioned in this question) is to set

myJsonObj.__proto__ = { function1: /* ... */, function2: /* ... */ };

However, as MDC helpfully points out, the __proto__ property is non-standard and deprecated. Is there any standards-compliant way (for some definition of "standards") to achieve the same effect, without having to create lots of new wrapper objects?

like image 488
kpozin Avatar asked Dec 10 '10 15:12

kpozin


People also ask

What is __ proto __ property?

The __proto__ property of Object. prototype is an accessor property (a getter function and a setter function) that exposes the internal [[Prototype]] (either an object or null ) of the object through which it is accessed.

What does __ proto __ in an object pointing to?

The __proto__ property is a default property added to every object. This property points to the prototype of the object. The default prototype of every object is Object. prototype .

What does __ proto __ mean in JavaScript?

__proto__ is a way to inherit properties from an object in JavaScript. __proto__ a property of Object. prototype is an accessor property that exposes the [[Prototype]] of the object through which it is accessed. POSTly is a web-based API tool that allows for fast testing of your APIs (REST, GraphQL).

What is the difference between [[ prototype ]] and __ proto __?

prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype. Current standards provide an equivalent Object.


1 Answers

There is no standards compliant way to change the prototype of an object after its creation. There is a standards compliant way to create objects with whatever prototype you desire while parsing from JSON.

From http://www.json.org/js.html:

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

like image 138
Mike Samuel Avatar answered Oct 12 '22 13:10

Mike Samuel