有一個類:
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
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));
在node v10.12.0以上版本中,使用了Symbol,并可以重寫[inspect]()函數。
相關文檔為:https://nodejs.org/api/util.html#util_util_inspect_custom