【发布时间】:2013-09-20 12:17:08
【问题描述】:
我有一个类似的对象
var Profile = Object.create(null);
Object.defineProperties(Profile, {
id: {
value: "",
enumerable: true
},
name: {
value: "",
enumerable: true
},
active: {
value: true,
enumerable: true
}
});
现在我想创建一个 Profile 实例并为其指定 id 和名称,并保持活动默认为 true,所以我这样做:
var p1 = Object.create(Profile, {
id: {
value: "123",
enumerable: true
},
name: {
value: "hello world",
enumerable: true
}
});
然后我得到了一个名为 p1 的对象,但我在其中找不到“活动”
Object.getOwnPropertyNames(p1);
我也不能使用 JSON.stringify(p1) 来序列化属性“active”,但我需要属性“active”可以是可序列化的。
这是我使用 Object.create 的错误方式吗?我只想创建一个可序列化的“类”并获得它的可序列化“实例”。我该怎么做?
【问题讨论】:
-
您的属性不可配置且不可写...
-
为什么不只是
{ id: "123", name: "hello world" }?无论如何,JavaScript 天生就是肮脏的...... -
@EliasVanOotegem 但是
p1.id还是变成了123 而p1.name变成了“hello world”,我不知道为什么...... -
@Virus721 因为我想要一个像“类”这样的模板来制作对象,并且它有一些默认值,我只需要更改一些与默认值不同的值然后得到一个“完整”目的。和这里一样,active不用改,我只写id和name,希望
JSON.stringify()可以序列化属性“active”但不行。 -
@Sunny:因为
active属性在您的p1对象中不存在。 You have to understand how JS resolves properties to their respective values。您在p1上调用JSON.stringify,该对象不知道任何active属性。直到你尝试访问p1.activeJS 才会检查Object.prototype之前的"parent" 对象,并尝试将表达式p1.active解析为一个值。
标签: javascript object serialization ecmascript-5