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.
2 Answers
Reset to default 7You 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'