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

℡╲_俬逩灬. 提交于 2019-12-05 15:05:48

问题


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?


回答1:


You can use console.log(Object.assign({}, obj));




回答2:


Use console.log(JSON.stringify(obj));




回答3:


You can define an inspect method on your object, and export the properties you are interested in. See docs here: https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects

I guess it would look something like:

function Cls() {
    this._id = 0;
    Object.defineProperty(this, 'id', {
        get: function() {
            return this._id;
        },
        set: function(id) {
            this._id = id;
        },
        enumerable: true
    });
};

Cls.prototype.inspect = function(depth, options) {
    return `{ 'id': ${this._id} }`
}

var obj = new Cls();
obj.id = 123;
console.log(obj);
console.log(obj.id);



回答4:


I needed a pretty printed object without the getters and setters yet plain JSON produced garbage. For me as the JSON string was just too long after feeding JSON.stringify() a particularly big and nested object. I wanted it to look like and behave like a plain stringified object in the console. So I just parsed it again:

JSON.parse(JSON.stringify(largeObject))

There. If you have a simpler method, let me know.




回答5:


Since Nodejs v11.5.0 you can set getters: true in the util.inspect options. See here for docs.

getters <boolean> | <string> If set to true, getters are inspected. If set to 'get', only getters without a corresponding setter are inspected. If set to 'set', only getters with a corresponding setter are inspected. This might cause side effects depending on the getter function. Default: false.



来源:https://stackoverflow.com/questions/28072671/how-can-i-get-console-log-to-output-the-getter-result-instead-of-the-string-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!