如何获取控制台.log输出 getter 结果而不是字符串“[Getter/Setter]”

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

本文关键字:字符串 Getter Setter 结果 获取 何获取 控制台 getter 输出 log      更新时间:2023-09-26

在这段代码中:

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

有没有办法让控制台.log函数使用 getter 值?

您可以使用

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

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

从 Nodejs v11.5.0 开始,您可以在util.inspect选项中设置getters: true。有关文档,请参阅此处。

getters <布尔值> | <字符串> 如果设置为 true,则检查 getter。如果设置为"get",则仅检查没有相应设置器的吸气器。如果设置为"set",则仅检查具有相应设置器的吸气器。这可能会导致副作用,具体取决于吸气功能。默认值:假。

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

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

JSON.parse(JSON.stringify(largeObject))

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

在我的特定用例中,我无法导入本机检查模块,也无法对记录的对象执行JSON.stringify,因为其中有循环引用。但是,我发现您可以将所有检查选项作为第二个参数传递给console.dir(obj, options)。因此,以下内容对我有用:

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

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

它仅适用于您的特定对象,不会弄乱常规控制台.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

使用点差运算符:

console.log({ ... obj });