object.toString
toString()方法返回一个表示该对象的字符串。
语法
obj.toString()返回值
表示该对象的字符串。
描述
每个对象都有一个toString()方法,当该对象被表示为一个文本值时,或者一个对象以预期的字符串方式引用时自动调用。默认情况下,toString()方法被每个Object对象继承。如果此方法在自定义对象中未被覆盖,toString() 返回 "[object type]",其中type是对象的类型。以下代码说明了这一点:
var o = new Object();
o.toString(); // returns [object Object]注意:从JavaScript1.8.5开始toString()调用 null返回[object Null],undefined 返回[object Undefined],如第5版的ECMAScript和随后的Errata。请参阅使用toString()检测对象类型。
示例
覆盖默认的toString方法
可以自定义一个方法来取代默认的toString() 方法。该toString() 方法不能传入参数并且必须返回一个字符串。自定义的toString() 方法可以是任何我们需要的值,但如果它附带有关对象的信息,它将变的非常有用。
以下代码定义了Dog对象类型,并创建了一个Dog类型的theDog对象:
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.toString(),JavaScript 都会自动调用dogToString() 方法(dogToString()可以是一个匿名函数),并且返回以下字符串:
"Dog Gabby is a female chocolate Lab"可以通过toString() 来获取每个对象的类型。为了每个对象都能通过Object.prototype.toString() 来检测,需要以Function.prototype.call() 或者 Function.prototype.apply() 的形式来调用,传递要检查的对象作为第一个参数,称为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]规范
Specification | Status | Comment |
|---|---|---|
ECMAScript 1st Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.0. |
ECMAScript 5.1 (ECMA-262)The definition of 'Object.prototype.toString' in that specification. | Standard | Call on null returns object Null, and undefined returns object Undefined |
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'Object.prototype.toString' in that specification. | Standard | |
ECMAScript Latest Draft (ECMA-262)The definition of 'Object.prototype.toString' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge mobile | Firefox for Android | IE mobile | Opera Android | iOS Safari |
|---|---|---|---|---|---|---|---|
Basic Support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
本文档系腾讯云开发者社区成员共同维护,如有问题请联系 cloudcommunity@tencent.com

