如何使用JSON.stringify()获取具有get / set序列化的属性

时间:2012-04-13 00:20:21

标签: javascript jquery javascript-objects ecmascript-5

我有以下情况:

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}

注意 test 不是原型定义,可枚举的 设置为 true

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

2 个答案:

答案 0 :(得分: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}

注意测试不是原型定义,并且可枚举的 设置为 true

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

答案 1 :(得分: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());

但是,如果您尝试序列化不可能的功能。