调整自定义对象的console.log行为 [英] adjust console.log behaviour of custom object

查看:94
本文介绍了调整自定义对象的console.log行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以影响console.log给出的自定义对象吗? 我试图覆盖customObject.prototype.toString方法,但该方法不起作用.

is there any way to influence what console.log gives out custom objects? I tried to overwrite the customObject.prototype.toString method, that did not work though.

有什么想法吗?

推荐答案

在node.js中, console.log 对每个参数调用 util.inspect ,而无需格式化占位符.因此,如果您在对象上定义inspect(depth, opts)方法,则将调用该方法以获取对象的自定义字符串表示形式.

In node.js, console.log calls util.inspect on each argument without a formatting placeholder. So if you define an inspect(depth, opts) method on your object it will be called to get your custom string representation of the object.

例如:

function Custom(foo) {
    this.foo = foo;
}

Custom.prototype.inspect = function(depth, opts) {
    return 'foo = ' + this.foo.toUpperCase();
};

var custom = new Custom('bar');
console.log(custom);

输出:

foo = BAR

foo = BAR

或使用课程:

class Custom {
    constructor(foo) {
        this.foo = foo;
    }

    inspect(depth, opts) {
        return 'foo = ' + this.foo.toUpperCase();
    }
}

var custom = new Custom('bar');
console.log(custom);

这篇关于调整自定义对象的console.log行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆