Search code examples
javascriptnode.jspropertiesconsolegetter-setter

How can I get console.log to output the getter result instead of the string "[Getter/Setter]"?


In this code:

function Cls() {
    this._id = 0;
    Object.defineProperty(this, 'id', {
        get: function() {
            return this._id;
        },
        set: function(id) {
            this._id = id;
        },
        enumerable: true
    });
};
var obj = new Cls();
obj.id = 123;
console.log(obj);
console.log(obj.id);

I would like to get { _id: 123, id: 123 } but instead I get { _id: 123, id: [Getter/Setter] }

Is there a way to have the getter value be used by the console.log function?


Solution

  • In my particular use-case I couldn't import the native inspect module, and I also couldn't do JSON.stringify on my logged object because there were circular references within it. But, I found that you can pass all of the inspect options as the second argument to console.dir(obj, options). Thus, the following worked for me:

    console.dir(myObj, { getters: true });