The front-end technology: how to output JSON format JS class instance in the console

There is a class:
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

 

If we are examples of output in the console:
console.log(new Point(10, 20));

 

The output console is:
Point { x: 10, y: 20 }

 

How that only output in JSON format, does not output the class name "Point" it?
 
Some students may use the following method:
console.log(JSON.stringify(new Point(10, 20)))

 

This method is certainly possible, the output results are as follows:
{"x":10,"y":20}

 

But every time our output, we need to call a JSON.stringify, a bit long-winded.
Is there a more concise way to do it?
The answer is yes.
In fact, if you are using nodejs, when output console.log class object, the function call is to inspect and print out the sequence of the object.
 
And there is a custom object inspection function of the way in the node.
In the 6.6.0 or later, you can override the class [util.inspect.custom] (depth, options) function.
 
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 versions of the documentation: https://nodejs.org/docs/latest-v8.x/api/util.html
 
In the above v10.12.0 node using the Symbol, and can rewrite [Inspect] () function.
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));
 

Guess you like

Origin www.cnblogs.com/popgis/p/11750179.html
Recommended