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);
}
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);
}
Share
Improve this question
asked Oct 29, 2010 at 1:04
camomilkcamomilk
7631 gold badge8 silver badges16 bronze badges
2 Answers
Reset to default 12You need to override the toString() function that all objects have. Try
TestObj.prototype.toString = function() {return this.sValue };
You should overload the toString
method ...
TestObj.prototype.toString = function(){return this.sValue;}
Example at http://jsfiddle/Ktp9E/