How to convert an object to a custom string in javascript?

I want to overload the conversion of an object to a string, so in the following example, the string "TEST" will be displayed instead of "[object Object]". How to do it?

function TestObj() { this.sValue = "TEST"; } function Test() { var x = new TestObj(); document.write(x); } 
+4
source share
2 answers

You must overload the toString method ...

 TestObj.prototype.toString = function(){return this.sValue;} 

Example http://jsfiddle.net/Ktp9E/

+7
source

You need to override the toString () function that all objects have. Try

 TestObj.prototype.toString = function() {return this.sValue }; 
+12
source

All Articles