我怎样才能得到安慰呢?将日志输出getter结果而不是字符串“[getter /Setter]”?

时间:2023-02-12 20:46:58

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] }

我想要得到{_id: 123, id: 123}但是我得到了{_id: 123, id: [Getter/Setter]}

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

是否有一种方法可以让控制台使用getter值。对数函数?

3 个解决方案

#1


6  

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

使用console.log(JSON.stringify(obj));

#2


6  

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

您可以使用console.log(对象。分配({ },obj));

#3


2  

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

您可以在对象上定义一个inspect方法,并导出感兴趣的属性。看到文档: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);

#1


6  

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

使用console.log(JSON.stringify(obj));

#2


6  

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

您可以使用console.log(对象。分配({ },obj));

#3


2  

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

您可以在对象上定义一个inspect方法,并导出感兴趣的属性。看到文档: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);