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

问题描述 投票:2回答:2

我有以下情况:

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方法,但这没有用。

任何帮助将不胜感激。

javascript jquery javascript-objects ecmascript-5
2个回答
2
投票

这对我有用:

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}

注意test不是原型定义,并且可枚举的[[has设置为true。

[我在IE9,FF 11和Chrome 18中测试了上述

工作

版本-所有这三个版本均提供了预期的结果。

1
投票
您需要将其应用于对象本身,而不是像这样的原型

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());

但是,如果您尝试序列化不可能的功能。
© www.soinside.com 2019 - 2024. All rights reserved.