How do I override the default output of an object?

前端 未结 2 1367
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);
    
    0 讨论(0)
  • 2020-12-18 15:34

    MyObj.prototype.toString() = function() {} will work, but won't output to the console. If you do something like

    console.log("The object says: " + obj);
    

    ... you will see the output of toString()

    function MyObj() {
        this.prop = "property";
    }
    MyObj.prototype.toString = function() {
       return "My property 'prop' has the value: '" + this.prop + "'";
    }
    var obj = new MyObj();
    console.log("the object says: " + obj);
    
    // the object says: My property 'prop' has the value: 'property'
    
    // Or call toString() explicitly
    console.log(obj.toString());
    // My property 'prop' has the value: 'property'
    
    0 讨论(0)
提交回复
热议问题