Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I want to overload the conversion of an object to a string, so that the following example would output the string "TEST" instead of "[object Object]". How do I do this?

function TestObj()
{
    this.sValue = "TEST";
}
function Test()
{
    var x = new TestObj();
    document.write(x);
}
like image 474
camomilk Avatar asked Dec 01 '22 04:12

camomilk


2 Answers

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

TestObj.prototype.toString = function() {return this.sValue };
like image 187
Jacob Mattison Avatar answered Dec 04 '22 12:12

Jacob Mattison


You should overload the toString method ...

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

Example at http://jsfiddle.net/Ktp9E/

like image 31
Gabriele Petrioli Avatar answered Dec 04 '22 13:12

Gabriele Petrioli