In Python, classes have a __repr__ method to override the default output of an instantiated object. Is there a similar method in Node.js?
Let’s say we have:
class Example{
constructor(){
this.Array = [1.2.3.4];
this.private_str = "What does the fox say? Dingdingdingdingdingding."}}Copy the code
If we instantiate the Example class Example, we print:
let e = new Example();
console.log(e);
Copy the code
The results are as follows:
Example {
Array: [ 1.2.3.4].private_str: 'What does the fox say? Dingdingdingdingdingding.'
}
Copy the code
But what if we don’t want anyone to know what the fox actually said, and we just want to output part of the Array?
In older versions of Node.js, there is a Deprecated method inspect() that has been Deprecated, but is no longer available.
We can override the inspect() method of our class in another way:
Customize the output on the console using [util.inspect.custom].
For example, let’s change our code a bit:
const util = require("util")
class Example{
constructor(){
this.Array = [1.2.3.4];
this.private_str = "What does the fox say? Dingdingdingdingdingding."
}
[util.inspect.custom](depth, options) {
return this.Array; }}let e = new Example();
console.log(e);
Copy the code
Output:
[ 1.2.3.4 ]
Copy the code
And you’re done!
Note: This method is not modifiedconsole.dir()
The output of the