在JavaScript中将JSON字符串解析为特定对象原型 [英] Parse JSON String into a Particular Object Prototype in JavaScript

查看:226
本文介绍了在JavaScript中将JSON字符串解析为特定对象原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何解析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
在做了一些研究之后,我想到了这个...

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.


  1. 使用 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)

  • Object.assign(new Foo, { a: 1 })
  • Object.setPrototypeOf({ a: 1 }, Foo.prototype)

这篇关于在JavaScript中将JSON字符串解析为特定对象原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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