Del*_*ens 2 javascript tostring
值是否必须返回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>
Run Code Online (Sandbox Code Playgroud)
正如Shiny和New先生所说,所有 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 + ")";
}
};
Run Code Online (Sandbox Code Playgroud)
现在,如果您创建new List(...)并调用其toString方法(或通过任何隐式将其转换为字符串的函数或运算符运行),toString将使用您的自定义方法.
最后,以检测对象是否有toString其类中定义的方法(注意,这将不与子类或对象的文字工作,也就是说作为一个练习为读者),就可以访问它constructor的prototype属性:
if (value.constructor.prototype.hasOwnProperty("toString")) {
alert("Value has a custom toString!");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1995 次 |
| 最近记录: |