How do I override the default output of an object?

前端 未结 2 1372
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: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'
    

提交回复
热议问题