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

标签 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不是原型(prototype)定义,可枚举必须设置为true

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

关于javascript - 如何使用 get/set 获取属性以使用 JSON.stringify() 进行序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10133665/

相关文章:

javascript - 将 Faker 与 Cypress 结合使用

javascript - 在 React 中渲染 JavaScript 对象

javascript - 在现有对象中添加新元素

javascript - 使用键简化对象的设置值

javascript - 截至今天,navigator.platform 的可能值列表是什么?

jquery - 如何改进 jQuery 显示/隐藏实现?

javascript - 禁用按钮 .Net Core MVC View

javascript - JQuery 提交的复选框值未定义

javascript - 在没有原型(prototype)的情况下创建的对象上使用 console.log 时出错 && 访问具有字符串属性的数组有效..如何?

javascript - token 的过期日期(Google OAuth2)和凭据有什么区别?