如何让 console.log 输出 getter 结果而不是字符串“[Getter/Setter]”?

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

在此代码中:

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));

您可以在您的对象上定义一个 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);

您可以使用console.log(Object.assign({}, obj));

我需要一个漂亮的打印对象,没有 getter 和 setter,但 JSON 会产生垃圾。对我来说,因为 JSON 字符串在输入 JSON.stringify() 一个特别大的嵌套对象后太长了。我希望它在控制台中看起来和行为都像一个普通的字符串化对象。所以我只是再次解析它:

JSON.parse(JSON.stringify(largeObject))

那里。如果你有更简单的方法,请告诉我。

从 Nodejs v11.5.0 开始,您可以在 util.inspect 选项中设置 getters: trueSee 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.

在 Node.js 上,我建议使用 util.inspect.custom,这将允许您将 getter 打印为值,同时保持其他属性输出不变。

它将仅适用于您的特定对象,不会混淆一般 console.log 输出。

Object.assign 相比的主要好处是它发生在您的对象上,因此您可以保留常规的通用 console.log(object) 语法。你不必用 console.log(Object.assign({}, object)).

包装它

将以下方法添加到您的对象中:

[util.inspect.custom](depth, options) {
    const getters = Object.keys(this);
    /*
        for getters set on prototype, use instead:
        const prototype = Object.getPrototypeOf(this);
        const getters = Object.keys(prototype);
    */
    const properties = getters.map((getter) => [getter, this[getter]]);
    const defined = properties.filter(([, value]) => value !== undefined);
    const plain = Object.fromEntries(defined);
    const object = Object.create(this, Object.getOwnPropertyDescriptors(plain));
    // disable custom after the object has been processed once to avoid infinite looping
    Object.defineProperty(object, util.inspect.custom, {});
    return util.inspect(object, {
        ...options,
        depth: options.depth === null ? null : options.depth - 1,
    });
}

这是您的上下文中的一个工作示例:

const util = require('util');

function Cls() {
    this._id = 0;
    Object.defineProperty(this, 'id', {
        get: function() {
            return this._id;
        },
        set: function(id) {
            this._id = id;
        },
        enumerable: true
    });
    this[util.inspect.custom] = function(depth, options) {
    const getters = Object.keys(this);
    /*
        for getters set on prototype, use instead:
        const prototype = Object.getPrototypeOf(this);
        const getters = Object.keys(prototype);
    */
    const properties = getters.map((getter) => [getter, this[getter]]);
    const defined = properties.filter(([, value]) => value !== undefined);
    const plain = Object.fromEntries(defined);
    const object = Object.create(this, Object.getOwnPropertyDescriptors(plain));
    // disable custom after the object has been processed once to avoid infinite looping
    Object.defineProperty(object, util.inspect.custom, {});
    return util.inspect(object, {
        ...options,
        depth: options.depth === null ? null : options.depth - 1,
    });
}
};
var obj = new Cls();
obj.id = 123;
console.log(obj);
console.log(obj.id);

输出:

Cls { _id: 123, id: 123 }
123