最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

oop - Create transient JavaScript variable in an object - Stack Overflow

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

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

What I want to do is stop displaying the id value. Is there a way to make the id variable tranient. Please help

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

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

What I want to do is stop displaying the id value. Is there a way to make the id variable tranient. Please help

Share Improve this question asked Apr 28, 2016 at 7:29 jayangaVliyanagejayangaVliyanage 832 silver badges12 bronze badges 1
  • 2 Possible duplicate of json stringify : How to exclude certain fields from the json string – James Thorpe Commented Apr 28, 2016 at 7:34
Add a ment  | 

3 Answers 3

Reset to default 4

Every object has a method toJSON(), which is invoked when the object should be serialize using JSON.stringify().

From MDN article on 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


The following example creates a different serialization function, which will exclude the _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'}

Check the working demo.

If you don't need to enumerate over this property you can use non-enumerable properties:

    function Player(name)
        {            
            this._name = name;                     
            Object.defineProperty(this, '_id', {
              enumerable: false
            });
        };

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

Targeting ES2022, you can achieve transient variables at least in 2 ways:

  1. Using a private variable
  2. Using an "accessor" variable
"use strict";
class Example {
    constructor() {
        this.#aTransientValue_accessor_storage = "transient";
        this.aNormalValue = "public";
        this.#aPrivateValue = "public";
    }
    #aTransientValue_accessor_storage;
    get aTransientValue() { return this.#aTransientValue_accessor_storage; }
    set aTransientValue(value) { this.#aTransientValue_accessor_storage = value; }
    #aPrivateValue;
}
const example = new Example();
console.log(example); /// prints { "aNormalValue": "public" }

Typescript even introduced the "accessor" keyword, which can be used for this purpose.

Here is the TS equivalent code:

class Example {
    accessor aTransientValue = "transient";
    public aNormalValue = "public"
    #aPrivateValue = "public"
}

const example = new Example();

console.log(example);
Post a comment

comment list (0)

  1. No comments so far