开发者

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

开发者 https://www.devze.com 2023-01-22 17:19 出处:网络
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?

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


You 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.net/Ktp9E/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号