Object.toString

概述

返回一个代表该对象的字符串.

Method of Object
Implemented in JavaScript 1.0
ECMAScript Edition ECMAScript 1st Edition

语法

object.toString()

描述

当对象需要转换为字符串时,会调用它的toString()方法. 默认情况下,每个对象都会从Object上继承到toString()方法,如果这个方法没有被这个对象自身或者更接近的上层原型上的同名方法覆盖(遮蔽),则调用该对象的toString()方法时会返回"[object type]",这里的字符串type表示了一个对象类型.下面的代码演示了这一点:

var o = new Object();
o.toString();           // 返回了[object Object]
从JavaScript 1.8.5(ES5)开始,null值上调用toString()方法会返回[object Null],类似的,undefined上会返回[object Undefined].查看使用toString方法检测对象类型一文了解详情.

示例

覆盖(遮蔽)默认的toString方法

You can create a function to be called in place of the default toString() method. The toString() method takes no arguments and should return a string. The toString() method you create can be any value you want, but it will be most useful if it carries information about the object.

The following code defines the Dog object type and creates theDog, an object of type Dog:

function Dog(name,breed,color,sex) {
   this.name=name;
   this.breed=breed;
   this.color=color;
   this.sex=sex;
}

theDog = new Dog("Gabby","Lab","chocolate","female");

If you call the toString() method on this custom object, it returns the default value inherited from Object:

theDog.toString(); //returns [object Object]

The following code creates and assigns dogToString() to override the default toString() method. This function generates a string containing the name, breed, color, and sex of the object, in the form "property = value;".

Dog.prototype.toString = function dogToString() {
  var ret = "Dog " + this.name + " is a " + this.sex + " " + this.color + " " + this.breed;
  return ret;
}

With the preceding code in place, any time theDog is used in a string context, JavaScript automatically calls the dogToString() function, which returns the following string:

Dog Gabby is a female chocolate Lab

使用toString()方法来检测对象类型

toString() can be used with every object and allows you to get its class. To use the Object.prototype.toString() with every object, you need to call Function.prototype.call() or Function.prototype.apply() on it, passing the object you want to inspect as the first parameter called thisArg.

var toString = Object.prototype.toString;

toString.call(new Date); // [object Date]
toString.call(new String); // [object String]
toString.call(Math); // [object Math]

//Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]

相关链接

Document Tags and Contributors

Contributors to this page: ziyunfei
最后编辑者: ziyunfei,