前端技術之:如何在控制台將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()
  }
}

 

 
在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));
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM