Is there an __repr__ equivalent for javascript?

前端 未结 8 1957
梦谈多话
梦谈多话 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:21

    JSON.stringify is probably the closest you are going to get from native libraries. It doesn't work well with objects, but you could define your own code to work around that. I searched for libraries that provide this functionality but didn't find anything.

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

    This is solution for NodeJS (not sure about browser). As https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_inspect_object_options says, you could add inspect(depth, opts) to your class and it will be called when you console.log(user_class_instance);

    Therefore this should do the trick:

    User.prototype.inspect = function(depth, opts){
        return this.name;
    };
    
    0 讨论(0)
提交回复
热议问题