Is there an __repr__ equivalent for javascript?

前端 未结 8 1956
梦谈多话
梦谈多话 2020-12-05 13:32

The closest I got to something close to Python\'s repr is this:

function User(name, password){
         this.name = name;
         this.pass         


        
相关标签:
8条回答
  • 2020-12-05 14:04
    String(user)
    

    Is the best I can think of. I think another alternative may be to find a 3rd party lib that handles creating human readable presentation for objects.

    0 讨论(0)
  • 2020-12-05 14:04

    A quick shortcut for me is to wrap the value with an array literal, like this:

    console.log([variable]);
    

    The output in the browser's developer console makes it quite clear what the only element of the array is.

    0 讨论(0)
  • 2020-12-05 14:08

    As Andrew Johnson said, JSON.stringify is probably the closest you can get out of the box.

    One common strategy for a repr is to output runnable Python code. If you want to do this, lave (opposite of eval) is a good choice.

    Example:

    var escodegen = require('escodegen')
    var lave = require('lave')
    
    function User(name, password){
                 this.name = name;
                 this.password = password;
    }
    
    var user = new User('example', 'password');
    
    console.log(lave(user, {generate: escodegen.generate}));
    

    Output (not as elegant as I had hoped!):

    var a = Object.create({ 'constructor': function User(name, password){
                 this.name = name;
                 this.password = password;
    } });
    a.name = 'example';
    a.password = 'password';
    a;
    
    0 讨论(0)
  • 2020-12-05 14:10

    Node v6.6.0 introduced the util.inspect.custom symbol: it is a globally registered symbol accessible through Symbol.for('nodejs.util.inspect.custom'). It can be used to declare custom inspect functions.

    Here's a usage example with OP's case:

    function User(name, password){
      this.name = name;
      this.password = password;
      this[Symbol.for('nodejs.util.inspect.custom')] = () => this.name;
    }
    
    var user = new User('example', 'password');
    
    console.log(user)  // 'example'
    
    0 讨论(0)
  • 2020-12-05 14:11

    In Nodejs, console.log representation of a Javascript object can be overridn by adding inspect() method to that Object

    eg:

    function User(name, password){
             this.name = name;
             this.password = password;
    }
    User.prototype.toString = function(){
        return this.name;
    };
    User.prototype.inspect = function(){ return 'Model: ' + this.name ; }
    

    -Thanks to 'Ciro Santilli'

    0 讨论(0)
  • 2020-12-05 14:12

    Node.js util.inspect

    http://nodejs.org/api/util.html#util_util_inspect_object_options

    To get the object representation that appears on the terminal as a string you can do:

    const util = require('util');
    console.log(util.inspect({ a: "0\n1", b: "c"}));
    // Equivalent: automatically called by `console.log`.
    console.log({ a: "0\n1", b: "c"});
    

    output:

    { a: '0\n1', b: 'c' }
    { a: '0\n1', b: 'c' }
    

    This is the same that would appear on the terminal if you copy pasted the string { a: "0\n1", b: "c"} into the terminal and pressed enter.

    Override the inspect method of a class for a custom representation

    This was asked at: How to change string representation of objects in Nodejs debug console view and mentioned at: https://stackoverflow.com/a/32866283/895245 and https://stackoverflow.com/a/54667225/895245 but here goes a fuller example:

    const util = require('util');
    
    class MyClass {
      constructor(a, b) {
        this.a = a;
        this.b = b;
      }
      [util.inspect.custom]() {
        return `a is ${this.a} and b is ${this.b}`;
      }
    }
    
    const my_object = new MyClass(1, 2);
    console.log(util.inspect(my_object));
    console.log(my_object);
    

    Output:

    a is 1 and b is 2
    a is 1 and b is 2
    

    The default inspect if we hadn't defined a custom [util.inspect.custom] would have been:

    MyClass { a: 1, b: 2 }
    

    That same representation also shows if you just directly inspect the object on a terminal:

    > my_object
    a is 1 and b is 2
    

    In older Node.js, the syntax used to be just:

    inspect(){}
    

    but that was deprecated with message:

    [DEP0079] DeprecationWarning: Custom inspection function on Objects via .inspect() is deprecated
    

    as mentioned at:

    • (node:71307) [DEP0079] DeprecationWarning
    • https://nodejs.org/api/util.html#util_util_inspect_custom
    • https://nodejs.org/api/deprecations.html#deprecations_dep0079_custom_inspection_function_on_objects_via_inspect

    Pretty print util.inspect with newlines and indentation

    Not possible? Sigh:

    • https://github.com/nodejs/node/issues/14638
    • Indented, multi-line logging in NodeJS

    One big advantage over JSON.stringify is that inspect takes care of circular dependencies for you. But without pretty print, it is a pain.

    Tested in Node.js v10.15.1.

    0 讨论(0)
提交回复
热议问题