我有以下情况:
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不是原型(prototype)定义,可枚举必须设置为true。
我在 IE9、FF 11 和 Chrome 18 中测试了上述工作版本 - 所有三个版本都给出了预期结果。
关于javascript - 如何使用 get/set 获取属性以使用 JSON.stringify() 进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10133665/