概述
toString() 方法返回一个代表该对象的字符串。
语法
object.toString()
描述
当对象需要转换为字符串时,会调用它的toString()方法.。默认情况下,每个对象都会从Object上继承到toString()方法,如果这个方法没有被这个对象自身或者更接近的上层原型上的同名方法覆盖(遮蔽),则调用该对象的toString()方法时会返回"[object type]",这里的字符串type表示了一个对象类型。下面的代码演示了这一点:
var o = new Object(); o.toString(); // 返回了[object Object]
在null值上调用toString()方法会返回[object Null],类似的,undefined上会返回[object Undefined]。查看使用toString方法检测对象类型一文了解详情.示例
覆盖(遮蔽)默认的toString方法
可以自定义个方法来取代默认的 toString() 方法。该 toString() 方法不能传入参数并且必须返回一个字符串。自定义的 toString() 方法可以是任何我们需要的值,but it will be most useful if it carries information about the object.
在下面的代码中,定义了一个 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");
如果当前的对象调用了 toString() 方法,它将会返回从 Object 继承下来的 toString() 方法的返回默认值:
theDog.toString(); //returns [object Object]
下面的代码中定义了一个叫做 dogToString() 的方法来覆盖默认的 toString() 方法。这个方法生成一个 "property = value" 形式的字符串,该字符串包含了当前对象的 name, breed,color 和 sex的值。
Dog.prototype.toString = function dogToString() {
var ret = "Dog " + this.name + " is a " + this.sex + " " + this.color + " " + this.breed;
return ret;
}
有了上面的这段代码之后,在上下文中任何时候使用 theDog ,JavaScript 都会自动调用 dogToString() 方法,并且返回下面的字符串内容:
Dog Gabby is a female chocolate Lab
使用toString()方法来检测对象类型
可以通过toString() 来获取每个对象的类型。为了每个对象都能通过 Object.prototype.toString() 来检测,需要以 Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,把需要检测的对象作为第一个参数传入。
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]
规范
| 规范版本 | 规范状态 | 注解 |
|---|---|---|
| ECMAScript 1st Edition. Implemented in JavaScript 1.0. | Standard | Initial definition. |
| ECMAScript 5.1 (ECMA-262) Object.prototype.toString |
Standard |
Call on |
| ECMAScript 2015 (6th Edition, ECMA-262) Object.prototype.toString |
Standard |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |