繁体   English   中英

如何使用 get/set 获取属性以使用 JSON.stringify() 进行序列化

[英]How to get a property with get/set to serialize with JSON.stringify()

我有以下场景:

var msp = function () { 
  this.val = 0.00;
  this.disc = 0;

};
Object.defineProperty(msp.prototype, "x", {
                        get: function () {return this.val - this.disc;},
                        toJSON: function () {return this.val - this.disc;},
                        enumerable: true,
                        configurable: true
                    });
var mp = new msp();
JSON.stringify(mp); // only returns {"val":0,"disc":0}

我希望我能以某种方式在defineProperty 调用中的属性“x”上设置一个toJSON 方法,但这不起作用。

任何帮助,将不胜感激。

这对我有用:

var obj = function() {
    this.val = 10.0;
    this.disc = 1.5;
    Object.defineProperties(this, {
        test: {
            get: function() { return this.val - this.disc; },
            enumerable: true
        }
    });    
};

var o = new obj;
o.test;
8.5
JSON.stringify(o);   // output: {"val":10,"disc":1.5,"test":8.5}

注意测试不是一个原型定义和枚举必须设置为true。

我在 IE9、FF 11 和 Chrome 18 中测试了上述工作版本 - 所有三个都给出了预期的结果。

您需要将它应用于对象本身而不是像这样的原型

var msp = function () { 
  this.val = 0.00;
  this.disc = 0;

};
msp.prototype.dif=function () {this.x = this.val - this.disc;return this;}

var mp = new msp();
JSON.stringify(mp.dif());

但是,如果您尝试序列化该函数,那是不可能的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM