前端技術之:如何在控制檯將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函數。

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/lates...
在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));

相關文檔爲:https://nodejs.org/api/util.h...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章