非常教程

JavaScript参考手册

对象 | Object

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()检测对象类型

可以通过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)

JavaScript

JavaScript 是一种高级编程语言,通过解释执行,是一门动态类型,面向对象(基于原型)的解释型语言。它已经由ECMA(欧洲电脑制造商协会)通过 ECMAScript 实现语言的标准化。它被世界上的绝大多数网站所使用,也被世界主流浏览器( Chrome、IE、FireFox、Safari、Opera )支持。JavaScript 是一门基于原型、函数先行的语言,是一门多范式的语言,它支持面向对象编程,命令式编程,以及函数式编程。它提供语法来操控文本、数组、日期以及正则表达式等,不支持 I/O,比如网络