什么时候使用.toString()是安全的?

时间:2009-06-26 19:48:31

标签: 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>

4 个答案:

答案 0 :(得分:5)

正如Mr. Shiny and 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 + ")";
    }
};

现在,如果您创建new List(...)并调用其toString方法(或通过隐式将其转换为字符串的任何函数或运算符运行),您的自定义toString方法将使用。

最后,检测对象是否为其类定义了toString方法(请注意,这将与子类或对象文字一起使用;这是作为练习读者),您可以访问其constructor的{​​{1}}属性:

prototype

答案 1 :(得分:4)

答案 2 :(得分:0)

document.write,与window.alert一样,在写入或返回任何内容之前调用其参数的toString方法。

答案 3 :(得分:0)

其他答案都是正确的,toString存在于所有Javascript对象上。

一般情况下,如果您想知道对象上是否存在函数,您可以这样测试:

if (obj.myMethod) {
    obj.myMethod();
}

当然,这并不能确保myMethod是函数而不是属性。但大概你会知道的。