如何为Object.define()定义的属性创建唯一的toJSON方法

How to create a unique toJSON method for a property defined by Object.define()

本文关键字:属性 创建 唯一 方法 toJSON 定义 Object define      更新时间:2023-09-26

假设我们有一个具有已定义属性的对象,该对象应指向另一个对象,如下所示:

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}