views:

39

answers:

2

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);
}
+11  A: 

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

TestObj.prototype.toString = function() {return this.sValue };
JacobM
+5  A: 

You should overload the toString method ...

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

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

Gaby