简体   繁体   English

使JSON.parse创建的对象继承自另一个类

[英]Making an object created by JSON.parse inherit from another class

I receive a bunch of objects via JSON which ultimately need to have some instance member functions. 我通过JSON收到一堆对象,最终需要有一些实例成员函数。

Is there a way to do this without copying the data? 有没有办法在不复制数据的情况下执行此操作?

For example: 例如:

var DataObject = function() {};
DataObject.prototype.add = function() { return this.a + this.b; };

var obj = JSON.parse('{"a":1, "b":2}');

// Do something to obj to make it inherit from DataObject

console.assert( obj.add() === 3 );

I've tried setting obj.prototype = DataObject.prototype but that doesn't seem to work. 我已经尝试过设置obj.prototype = DataObject.prototype但这似乎不起作用。 What am I missing? 我错过了什么?

Well, in ECMAScript6 (in IE11, and every other non ie browser today), that would be __proto__ 好吧,在ECMAScript6中(在IE11中,以及今天所有其他非浏览器),这将是__proto__

obj.__proto__ = Object.create(DataObject.prototype);

[ fiddle ] [ 小提琴 ]

Generally, make sure you only do this at the object creation case, otherwise it can be very risky to do. 通常,请确保您在对象创建案例中执行此操作,否则可能会非常危险。

Also note, setting the protoype explicitly is not always faster than copying two properties, as you can see here so you have to be sure there is actual gain here. 另请注意,明确设置原型并不总是比复制两个属性更快, 正如您在此处所见,因此您必须确保此处有实际增益。

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

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