gpt4 book ai didi

javascript - 在对象中创建 transient JavaScript 变量

转载 作者:行者123 更新时间:2023-11-29 19:13:39 26 4
gpt4 key购买 nike

function Player(name)
{
this._name = name;
this._id = "Player"+(Player_ID++);
};

var newPlayer = new Player(newUnitName);
alert(JSON.stringify(newPlayer));

我想做的是停止显示 id 值。有没有办法让 id 变量变 transient 。请帮忙

最佳答案

每个对象都有一个方法 toJSON(),当对象应该使用 JSON.stringify() 序列化时调用该方法。

来自 MDN article在 JSON.stringify() 上:

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized


以下示例创建了一个不同的序列化函数,它将排除 _id:

var Player_ID = 0;
function Player(name) {
this._name = name;
this._id = "Player"+(Player_ID++);
this.toJSON = function() {
return {
_name: this._name
};
};
};

var newPlayer = new Player('Name 1');
console.log(JSON.stringify(newPlayer)); // prints {"_name": 'Name 1'}

检查工作demo .

关于javascript - 在对象中创建 transient JavaScript 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36908092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com