简体   繁体   English

分配给__proto__属性的正确方法

[英]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. 我有一些从JSON反序列化的对象,我想分配一个新的原型,以提供各种getter和setter函数。 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. 但是,正如MDC帮助指出的那样__proto__属性是非标准的并且已弃用。 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? 是否有任何符合标准的方法(对于某些“标准”的定义)来实现相同的效果,而不必创建大量新的包装器对象?

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. 在从JSON解析时,有一种符合标准的方法来创建具有所需原型的对象。

From http://www.json.org/js.html : 来自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. 可选的reviver参数是将在最终结果的每个级别为每个键和值调用的函数。 Each value will be replaced by the result of the reviver function. 每个值都将被reviver函数的结果替换。 This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects. 这可用于将通用对象重构为伪类的实例,或将日期字符串转换为Date对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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