前端技术之:如何在控制台将JS class实例输出为JSON格式
有一个类: class Point { constructor(x, y) { this.x = x; this.y = y; } } 如果我们在控制台中输出其实例: console.log(new Point(10, 20)); 控制台中的输出结果为: Point { x: 10, y: 20 } 那如何只输出JSON格式,不输出类名”Point”呢? 有的同学可能会使用如下的方法: console.log(JSON.stringify(new Point(10, 20))) 这种方法当然是可以的,其输出结果如下: {"x":10,"y":20} 但我们每次输出的时候,都需要调用一次JSON.stringify,显得有些啰嗦。 有没有一种更简洁的办法呢? 答案是肯定的。 实际上,如果你使用的是nodejs,console.log输出类对象时,是调用的inspect函数来序列化并打印输出对象的。 而在node中有一种自定义对象inspection函数的办法。 在6.6.0以上版本中,你可以重写类的[util.inspect.custom](depth, options)函数。 const util = require('util'); class Point { constructor(x, y) { this.x = x; this.y = y; } toString() {