温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎样在控制台将JS class实例输出为JSON格式

发布时间:2021-10-09 09:37:02 来源:亿速云 阅读:131 作者:柒染 栏目:web开发

怎样在控制台将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() {
    const that = this;
    return JSON.stringify(that);
  }

  [util.inspect.custom](depth, options) {
    return this.toString()
  }
}

8.x版本的文档说明:https://nodejs.org/docs/latest-v8.x/api/util.html
在node v10.12.0以上版本中,使用了Symbol,并可以重写[inspect]()函数。

const inspect = Symbol.for('nodejs.util.inspect.custom');

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    const that = this;
    return JSON.stringify(that);
  }

  [inspect]() {
    return this.toString()
  }
}

console.log(new Point(10, 20));

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI