我有以下情况:
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不是原型定义,并且可枚举的[[has设置为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());
但是,如果您尝试序列化不可能的功能。