在这段代码中:
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);
我想得到{_id:123,id:123}
但我得到{_id:123,id:[Getter / Setter]}
有没有办法让console.log函数使用getter值?
使用 console.log(JSON.stringify(obj));
您可以使用 console.log(Object.assign({}, obj));
你可以定义一个 inspect
对象上的方法,并导出您感兴趣的属性。请参阅此处的文档: https://nodejs.org/api/util.html#util_custom_inspection_functions_on_objects
我猜它会是这样的:
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);