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

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)

Mr.*_* 安宇 5

JavaScript中的每个对象都有一个toString()方法。

  • 那很有意思。感谢您纠正我。无论如何,仍然值得指出的是,在某些情况下toString不安全使用。 (2认同)

Ben*_*ank 5

正如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其类中定义的方法(注意,这将与子类或对象的文字工作,也就是说作为一个练习为读者),就可以访问它constructorprototype属性:

if (value.constructor.prototype.hasOwnProperty("toString")) {
    alert("Value has a custom toString!");
}
Run Code Online (Sandbox Code Playgroud)