生成 JSON 以转换为 ECMAScript 5 就绪消费
我希望能够以 ES5 风格定义某些属性: prop: { value: '1', enumerable: false, writable: true }
,但是有一个问题。
首先,JSON.parse() 只是将“可枚举”和“可写”属性解释为通用 JavaScript 对象的通用属性。这可能是预期和理想的行为,但是对于新的 ES5 属性来说,这是“解析”JSON 的类似方法吗?
其次,Object.create() 可以工作,但它有一些限制。例如,
//Native works
var prop = Object.create(Object.prototype, { prop: { value: '1', enumerable: false, writable: true } });
//prop === "1"
//Parse works
var prop = Object.create(Object.prototype, JSON.parse({ "prop": { "value": '1', "enumerable": false, "writable": true } });
//prop === "1"
//Parse fails
var prop = Object.create(Object.prototype, JSON.parse({ "prop": { "value": '1', "enumerable": "false", "writable": "true" } });
// prop === JSON.parse({ "prop": { "value": '1', "enumerable": "false", "writable": "true" } })
这里的问题当然是 "true" !== true
,它指示 Object.create()
返回与 相同的对象JSON.parse()。此外,要么是因为对特定 prop 属性的真实评估,要么是因为我试图创建特别大的对象,
Object.create()
似乎非常脆弱。
有没有更好的方法以尊重 ES5 prop 属性的方式“解析”这些对象?
In my client/server web app, I am generating large JSON strings (using JSON.NET JToken classes in C# web services) which I pass via AJAX Get requests to the client.
I would like to be able to define certain properties in the ES5 style: prop: { value: '1', enumerable: false, writable: true }
, but there's a hitch.
First, JSON.parse() simply interprets the 'enumerable' and 'writable' properties as generic properties on a generic JavaScript object. This is probably expected and desirable behavior, but is the a comparable method to 'parse' the JSON with respect to new ES5 property attributes?
Second, Object.create() works, but it has some limitations. For example,
//Native works
var prop = Object.create(Object.prototype, { prop: { value: '1', enumerable: false, writable: true } });
//prop === "1"
//Parse works
var prop = Object.create(Object.prototype, JSON.parse({ "prop": { "value": '1', "enumerable": false, "writable": true } });
//prop === "1"
//Parse fails
var prop = Object.create(Object.prototype, JSON.parse({ "prop": { "value": '1', "enumerable": "false", "writable": "true" } });
// prop === JSON.parse({ "prop": { "value": '1', "enumerable": "false", "writable": "true" } })
The problem here, of course, is that "true" !== true
, which instructs Object.create()
to return the same object as JSON.parse()
. Further, either because of the truthy evaluation of a particular prop attribute OR because I'm attempting to create particularly large objects, Object.create()
seems to be quite fragile.
Is there a better way to "parse" these objects in a way that respects the ES5 prop attributes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论