最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I override the default console.log() output of an object? - Stack Overflow

programmeradmin1浏览0评论

Say in JavaScript I create a simple object:

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

Now if I create an instance of this and the output it to console I see the object representation:

var obj = new MyObj();
console.log(obj);

How can I instead make that output a string?: For example, I would like that the console displays My property value is 'property' rather than [object object].

I've tried using MyObj.prototype.toString, but it doesn't seem to work.

Say in JavaScript I create a simple object:

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

Now if I create an instance of this and the output it to console I see the object representation:

var obj = new MyObj();
console.log(obj);

How can I instead make that output a string?: For example, I would like that the console displays My property value is 'property' rather than [object object].

I've tried using MyObj.prototype.toString, but it doesn't seem to work.

Share Improve this question edited Jan 18 at 19:38 S.Serpooshan 7,5005 gold badges35 silver badges63 bronze badges asked Mar 30, 2012 at 12:46 shanethehatshanethehat 15.6k11 gold badges59 silver badges87 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

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);

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)

  1. 暂无评论