如何在javascript中将对象转换为自定义字符串? [英] How do I convert an object to a custom string in javascript?

查看:56
本文介绍了如何在javascript中将对象转换为自定义字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重载对象到字符串的转换,因此下面的示例将输出字符串"TEST"而不是"[object Object]".我该怎么做?

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

推荐答案

您应该重载 toString 方法...

You should overload the toString method ...

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

http://jsfiddle.net/Ktp9E/

这篇关于如何在javascript中将对象转换为自定义字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆