题
不值已返回的toString()能够调用value.toString()?当你知道你可以调用value.toString()?
<script>
var newList = function(val, lst)
{
return {
value: val,
tail: lst,
toString: function()
{
var result = this.value.toString();
if (this.tail != null)
result += "; " + this.tail.toString();
return result;
},
append: function(val)
{
if (this.tail == null)
this.tail = newList(val, null);
else
this.tail.append(val);
}
};
}
var list = newList("abc", null); // a string
list.append(3.14); // a floating-point number
list.append([1, 2, 3]); // an array
document.write(list.toString());
</script>
其他提示
如先生闪亮与新状态,的所有的JavaScript对象有toString
方法。但是,该方法并不总是有用的,特别是对自定义类和对象文字,这往往返回字符串等"[Object object]"
。
您可以通过添加一个功能,使用该名称以类的原型创建自己的toString
方法,就像这样:
function List(val, list) {
this.val = val;
this.list = list;
// ...
}
List.prototype = {
toString: function() {
return "newList(" + this.val + ", " + this.list + ")";
}
};
现在,如果你创建一个new List(...)
并调用其toString
方法(或通过其转换为字符串隐含的任何功能或操作员运行),将使用您的自定义toString
方法。
最后,以检测对象是否为它的类中定义的toString
方法(注意,这将的不强>使用子类或对象文字工作的,也就是说留给读者作为练习读者),则可以访问其constructor
的prototype
属性:
if (value.constructor.prototype.hasOwnProperty("toString")) {
alert("Value has a custom toString!");
}
文件撰写,像window.alert,调用它的参数的toString方法将其写入或返回任何内容之前。
其他答案是正确的所有的JavaScript对象存在toString
。
在一般情况下,不过,如果你想知道,如果你的对象上存在的功能,你可以测试它像这样:
if (obj.myMethod) {
obj.myMethod();
}
这并不当然,确保myMethod
是一个函数,而不是一个属性。但想必你会知道的。
不隶属于 StackOverflow