假设我们有一个具有已定义属性的对象,该对象应指向另一个对象,如下所示:
Object.defineProperty(parent, 'child', {
enumerable: true,
get: function() { return this._actualChild; },
set: function(v){
if(v && typeof v === 'object'){
this._actualChild = v;
} else {
throw new TypeError('child property must be an object!')
}
}
});
有没有一种方法可以配置属性本身,使其在运行JSON.stringify()
时,.child
属性的toJSON可以为该属性唯一地定义?
例如,在我们设置了以下内容之后:
var jill = {id: 3, name: 'Jill'};
parent.child = jill;
如果我们可以以某种方式为parent.child定义toJSON
以返回子级的id
属性。因此JSON.stringify(parent)
将返回:
{_actualChild: {id: 3, name: 'Jill'}, child: 3}
当然,我们可以为子对象本身定义一个toJSON,但随后我们会得到:
{_actualChild: 3, child: 3}
我想将属性toJSON方法与实际子对象的toJSON方法分开。这可能吗?
如果我能做这样的事情那就太好了:
Object.defineProperty(o, 'child', {
enumerable: true,
get: function() {
return this._hiddenChild;
},
set: function(v){
if(v && typeof v === 'object'){
this._hiddenChild = v;
}
else {
throw new TypeError('child property must be an object!')
}
},
toJSON : function() {
return this._hiddenChild.id;
}
});
但是遗憾的是,Object.defineProperty
不采用toJSON
描述符。
否,不能为单个属性定义字符串化行为。您需要在parent
对象本身上放置一个toJSON
方法:
var parent = {};
Object.defineProperty(parent, "child", {…});
parent.child = …;
parent.toJSON = function() {
return {_actualChild:this.child, child:this.child.id};
};
> JSON.stringify(parent)
{"_actualChild":{"id":3,"name":"Jill"},"child":3}