将 JSON 字符串解析为 JavaScript 中的特定对象原型 [英] Parse JSON String into a Particular Object Prototype in JavaScript
问题描述
我知道如何解析 JSON 字符串并将其转换为 JavaScript 对象.您可以在现代浏览器(和 IE9+)中使用 JSON.parse()
.
I know how to parse a JSON String and turn it into a JavaScript Object.
You can use JSON.parse()
in modern browsers (and IE9+).
那太好了,但是我怎样才能把那个 JavaScript 对象变成一个特定 JavaScript 对象(即具有某个原型)?
That's great, but how can I take that JavaScript Object and turn it into a particular JavaScript Object (i.e. with a certain prototype)?
例如,假设您有:
function Foo()
{
this.a = 3;
this.b = 2;
this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
同样,我并不想知道如何将 JSON 字符串转换为通用 JavaScript 对象.我想知道如何将 JSON 字符串转换为Foo"对象.也就是说,我的对象现在应该有一个函数test"和属性a"和b".
Again, I am not wondering how to convert a JSON string into a generic JavaScript Object. I want to know how to convert a JSON string into a "Foo" Object. That is, my Object should now have a function 'test' and properties 'a' and 'b'.
更新经过一番研究,我想到了这个......
UPDATE After doing some research, I thought of this...
Object.cast = function cast(rawObj, constructor)
{
var obj = new constructor();
for(var i in rawObj)
obj[i] = rawObj[i];
return obj;
}
var fooJSON = Object.cast({"a":4, "b": 3}, Foo);
那行得通吗?
2017 年 5 月更新:执行此操作的现代"方式是通过 Object.assign
,但此功能在 IE 11 或更旧的 Android 浏览器中不可用.
UPDATE May, 2017: The "modern" way of doing this, is via Object.assign
, but this function is not available in IE 11 or older Android browsers.
推荐答案
当前的答案包含大量手卷或库代码.这是没有必要的.
The current answers contain a lot of hand-rolled or library code. This is not necessary.
使用
JSON.parse('{"a":1}')
创建一个普通对象.
使用标准化函数之一设置原型:
Use one of the standardized functions to set the prototype:
Object.assign(new Foo, { a: 1 })
Object.setPrototypeOf({ a: 1 }, Foo.prototype)
这篇关于将 JSON 字符串解析为 JavaScript 中的特定对象原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!