toString() 方法返回一个表示该对象的字符串。该方法旨在重写(自定义)派生类对象的类型转换的逻辑。
- JavaScript 调用 toString 方法将对象转换为一个原始值
- 字符串的强制转换转换优先调用
- 数字的强制转换和原始值的强制转换会优先调用
valueOf(),然后使用toString()方法通常在结束时调用,除非对象重写了valueOf() - 当你创建一个自定义对象时,你可以重写
toString()以调用自定义方法,以便将自定义对象转换为一个字符串 - 增加一个 @@toPrimitive 方法,优先于 valueOf 或 toString
Object.prototype.toString() 返回 "[object Type]",这里的 Type 是对象的类型。如果对象有 Symbol.toStringTag 属性,其值是一个字符串,则它的值将被用作 Type。
许多内置的对象,包括 Map 和 Symbol,都有 Symbol.toStringTag。一些早于 ES6 的对象没有 Symbol.toStringTag,但仍然有一个特殊的标签。它们包括(标签与下面给出的类型名相同):
Array、Function、Error、Boolean、Number、String、Date、RegExp、Arguments、Undefined、null
其他所有内容,包括用户自定义的类,除非有一个自定义的 Symbol.toStringTag,否则都将返回 "[object Object]"
为自定义对象重写 toString
class Dog {
constructor(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
}
const theDog = new Dog("Gabby", "Lab", "chocolate", "female");
theDog.toString(); // "[object Object]"
`${theDog}`; // "[object Object]"
toString() {
return `Dog ${this.name} is a ${this.sex} ${this.color} ${this.breed}`;
}
`${theDog}`; // "Dog Gabby is a female chocolate Lab"
使用 toString() 去检查对象类
const toString = Object.prototype.toString;
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
// Math has its Symbol.toStringTag
toString.call(Math); // [object Math]
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]
myDate[Symbol.toStringTag] = "myDate";
Object.prototype.toString.call(myDate); // [object myDate]
Date.prototype[Symbol.toStringTag] = "prototype polluted";
Object.prototype.toString.call(new Date()); // [object prototype polluted]