如何为Object.define()定义的属性创建唯一的toJSON方法
How to create a unique toJSON method for a property defined by Object.define()
假设我们有一个具有已定义属性的对象,该对象应指向另一个对象,如下所示:
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}
相关文章:
- 使用导航属性创建Kendo UI网格模型的问题
- Reactjs基于jsx中的属性创建条件组件
- JQuery 从类选择器上的数据属性创建一个数组
- 基于对象属性创建数组
- 融合图表 - 如何获取使用链接属性创建的更新融合图表 json
- 从 ASP.NET Web 窗体中的服务器端属性创建 JavaScript 条件
- 如何从子对象属性创建新数组
- 按属性创建唯一对象的数组
- 使用DOM中定义的html5数据属性创建新元素
- 使用JavaScript中的过滤元素属性创建对象
- 使用现有对象属性创建javascript对象
- 如何为Object.define()定义的属性创建唯一的toJSON方法
- 使用innerHTML属性创建页面加载计数器
- 根据指定的数据属性创建一个包含值和文本的select下拉选项
- 使用其他对象的属性创建对象
- 作为类的函数-为私有属性创建getter和setter
- 当鼠标悬停在由相同数据条目的不同属性创建的圆形元素时,我如何显示/隐藏文本元素?
- jQuery用动态ID和定义的CSS属性创建DIV(定义该DIV的外观和位置)
- 如何在ECMAScript 5: Object中配置属性.创建或定义对象属性
- 附加一个作为对象属性创建的元素