分配给__proto__属性的正确方法 [英] Proper way of assigning to __proto__ property

查看:141
本文介绍了分配给__proto__属性的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些从JSON反序列化的对象,我想为其分配一个新的原型,以提供各种getter和setter函数.一种明显的方法(如此问题所述a>)设置

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: /* ... */ };

但是,正如MDC 有用地指出__proto__属性是非标准的,不建议使用.是否有任何符合标准的方式(对于标准"的某种定义)都可以达到相同的效果,而不必创建很多新的包装器对象?

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?

推荐答案

没有标准的兼容方法可以在对象创建后更改其原型. 从JSON解析时,有一种符合标准的方法可以创建具有所需原型的对象.

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.

来自 http://www.json.org/js.html :

可选的reviver参数是 每个函数都会被调用 各个层面的关键和价值 最后结果.每个值将是 取而代之的是复活的结果 功能.这可以用来改革 将通用对象转换为 伪类,或转换日期 字符串插入Date对象.

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.

这篇关于分配给__proto__属性的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆