How do I override the default output of an object?

前端 未结 2 1366
Happy的楠姐
Happy的楠姐 2020-12-18 15:00

Say in JavaScript I create a simple object:

function MyObj() {
    this.prop = \"property\";
}

Now if I create an instance of this and the

2条回答
  •  执念已碎
    2020-12-18 15:32

    You could hook the browser console, and redefine it afterwards:

    var obj = {
        name: "Joel",
        age: 32,
        toString: function() {
            return this.name + " is " + this.age + " years old.";
        }
    };
    
    var browserConsole = console;
    
    console = {
        log: function(data) {
            if (typeof data === "object") {
                browserConsole.log(data.toString());
            } else {
                browserConsole.log(data);
            }
        }
    }
    
    console.log(obj);
    

提交回复
热议问题