Design A Javascript Object To Output To Console.log As A String As Per New Date()
How is it that console.log(new Date()); shows a string at the console? How do I imitate that behaviour in my objects?
Solution 1:
Provide a .toString()
method in your object's prototype:
varDemo = function(){};
Demo.prototype.toString = function(){ return"Demo string"; };
var test = newDemo();
console.log(test); // results in "Demo string"
Note that this could slightly alter the behaviour of your code, since the non-type safe comparison operator ==
will use this function in some circumstances if the left and right hand side are not of the same type:
if(test == "Demo String"){
console.log("Equal!");
}
if(test !== "Demo String"){
console.log("But not same type!");
}
However, it seems that console.log
hasn't been standardized yet, so there is no uniform solution. Note that you can still use console.log(test + "")
to trigger the call of toString
.
Post a Comment for "Design A Javascript Object To Output To Console.log As A String As Per New Date()"