从console.log自定义打印? [英] Custom printing from console.log?

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

问题描述

假设我有这堂课.

class Attribute {
  constructor(name) {
    this.name = name;
  }
}

然后我创建一个实例并将其记录到控制台以进行调试.

And I create an instance and log it to the console for debugging purposes.

const test = new Attribute('Large');
console.log(test);

如何获取它以输出特殊格式的字符串(如{Attribute} Large)?我主要关心的是Chrome支持,但是Node和其他浏览器也很好.

How can I get it to output a specially formatted string, like {Attribute} Large? I'm primarily concerned with Chrome support, but Node and other browsers would be nice, too.

推荐答案

class Attribute {
  constructor(name) {
    this.name = name;
  }
  toString(){//simply set the to String method?
    return "{Attribute} "+this.name;
  }
}

由于console.log不会调用String,因此您也可以这样做:

As console.log does not call to String you either do:

const test = new Attribute('Large');
console.log(test+"");

或者您创建自己的日志记录功能

or you create your own logging function

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

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