When creating a x = new Date()
object, if you put it into console.log(x)
a string will be output.
Is there a way to make a custom object that w
There is a function for that, toString, however if you just do console.log(new Test)
it will still output the object. But if your force it so print a string it will work: console.log('%s', new Test)
:
function Test() {
}
Test.prototype.toString =
function () {
return "Something else";
}
console.log("%s", new Test);
> Something else
Or if you concatenate it with another string:
var a = new Test;
console.log('Result: ' + a);
> Result: Something else
I use this a lot in my code to display a summary of the content of a object with data.
There is also valueOf:
Test.prototype.valueOf =
function () {
return 42;
}
console.log("%d", new Test);
> 3