5

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);
}

2 Answers 2

12

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

TestObj.prototype.toString = function() {return this.sValue };
Sign up to request clarification or add additional context in comments.

Comments

7

You should overload the toString method ...

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.