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

前端 未结 4 739
情歌与酒
情歌与酒 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条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-23 18:58

    There is a function for that, toString, however if you just do console.log(new Test) it will still output the object. But if your force it so print a string it will work: console.log('%s', new Test):

    function Test() {
    }
    
    Test.prototype.toString =
      function () {
        return "Something else";
      }
    
    
    console.log("%s", new Test);
    
    > Something else
    

    Or if you concatenate it with another string:

    var a = new Test;
    console.log('Result: ' + a);
    
    > Result: Something else
    

    I use this a lot in my code to display a summary of the content of a object with data.

    There is also valueOf:

    Test.prototype.valueOf =
      function () {
        return 42;
      }
    
    console.log("%d", new Test);
    
    > 3
    

提交回复
热议问题