javascript - how to get an object to return a value that is not the object itself

前端 未结 4 738
情歌与酒
情歌与酒 2021-01-23 18:07

When creating a x = new Date() object, if you put it into console.log(x) a string will be output.

Is there a way to make a custom object that w

4条回答
  •  闹比i
    闹比i (楼主)
    2021-01-23 18:57

    Overwrite toString of an Object:

    My comment above refered to toString as well. You can use JSON.stringify to print out all properties of an object on the fly within an object's toString method:

    function MyObject() {
      this.a = 'a';
      this.b = 'b';
      this.c = 'c';
    }
    
    MyObject.prototype.toString = function () {
      return JSON.stringify(this);
    };
    
    console.log((new MyObject()).toString()); // {"a":"a","b":"b","c":"c"}
    // or
    console.log('new MyObject(): ' + new MyObject()); // new MyObject(): {"a":"a","b":"b","c":"c"}
    

    Overwrite console.log:

    Another try might be to overwrite console.log to print always strings (only tested in FF!):

    // initialize this only once so that console.log prints out correctly
    
    (function () {
      var oldConsole = console.log;
      console.log = function (obj) {
        oldConsole(JSON.stringify(obj));
      };
    }) ();
    
    // now console.log prints strings
    console.log({
      a: 'a'
    }); // String: {"a":"a"}
    
    console.log(new Date()); // String: "2017-01-19T19:09:49.673Z"
    
    console.log(document); // String: {"location":{"href":"http://stackoverflow.com/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121#41749121","origin":"http://stackoverflow.com","protocol":"http:","host":"stackoverflow.com","hostname":"stackoverflow.com","port":"","pathname":"/questions/41748793/javascript-how-to-get-an-object-to-return-a-value-that-is-not-the-object-itsel/41749121","search":"","hash":"#41749121"},"jQuery112409140067213472354":3}
    

提交回复
热议问题