我们再来看一下 Object 以及其原型上的 toString 方法:
Object.toString(); // "function Object() { [native code] }"
Object.prototype.toString(); // "[object Object]"
var o = new Object();
console.log(o.toString()); // 返回 [object Object]
console.log(o.__proto__.toString()); // 返回 [object Object]
console.log(o.__proto__.toString === Object.prototype.toString); // true
我们可以看出 Object 和它的原型链上各自有一个 toString 方法,Object 输出的是其函数体 "function Object() { [native code] }",而 Object 原型上输出的是其类型 "[object Object]"。
数据类型 | 例子 | 输出 |
字符串 | "foo".toString() | "foo" |
数字 | 1.toString() | Uncaught SyntaxError: Invalid or unexpected token |
布尔值 | true.toString() | "true" |
undefined | undefined.toString() | Uncaught TypeError: Cannot read property 'toString' of undefined |
null | null.toString() | Uncaught TypeError: Cannot read property 'toString' of null |
String | String.toString() | "function String() {[native code]}" |
Number | Number.toString() | "function Number() {[native code]}" |
Boolean | Boolean.toString() | "function Boolean() {[native code]}" |
Array | Array.toString() | "function Array() {[native code]}" |
Function | Function.toString() | "function Function() {[native code]}" |
Date | Date.toString() | "function Date() {[native code]}" |
RegExp | RegExp.toString() | "function RegExp() {[native code]}" |
Error | Error.toString() | "function Error() {[native code]}" |
Promise | Promise.toString() | "function Promise() {[native code]}" |
Object | Object.toString() | "function Object() {[native code]}" |
Math | Math.toString() | "[object Math]" |
Window | Window.toString() | "function Window() { [native code] }" |
window | window.toString() | "[object Window]" |
数据类型调用 toString() 方法的返回值,由此我们看出不同的数据类型都有其自身toString()方法
// Boolean 类型,tag 为 "Boolean"
console.log(Object.prototype.toString.call(true)); // => "[object Boolean]"
// Number 类型,tag 为 "Number"
console.log(Object.prototype.toString.call(1)); // => "[object Boolean]"
// String 类型,tag 为 "String"
console.log(Object.prototype.toString.call("")); // => "[object String]"
// Array 类型,tag 为 "String"
console.log(Object.prototype.toString.call([])); // => "[object Array]"
// Arguments 类型,tag 为 "Arguments"
console.log(Object.prototype.toString.call((function() {
return arguments;
})())); // => "[object Arguments]"
// Function 类型, tag 为 "Function"
console.log(Object.prototype.toString.call(function(){})); // => "[object Function]"
// Error 类型(包含子类型),tag 为 "Error"
console.log(Object.prototype.toString.call(new Error())); // => "[object Error]"
// RegExp 类型,tag 为 "RegExp"
console.log(Object.prototype.toString.call(/d+/)); // => "[object RegExp]"
// Date 类型,tag 为 "Date"
console.log(Object.prototype.toString.call(new Date())); // => "[object Date]"
// 其他类型,tag 为 "Object"
console.log(Object.prototype.toString.call(new class {})); // => "[object Object]"
// window 全局对象
console.log(Object.prototype.toString.call(window); // => "[object Window]")