你可以把Object.prototype.toString(或简化版)想象成这样:
Object.prototype.toString = function() {
var myType = (typeof this)[0].toUpperCase() + (typeof this).substr(1);
return "[Object " + myType + "]";
}
(不相关:请参阅答案底部的注释以了解 (typeof this)[0] 的作用,但现在假设 myType = 'String' 用于字符串,'Array' 用于数组等)
它与[].toString() 不同,因为数组只是对象的子对象,toString for array 只是被覆盖:
Array.prototype.toString = function() {
return this.join(',');
}
当您调用Object.prototype.toString 时,您指的是第一个函数,而[].toString 指的是第二个函数。这与您这样做没有什么不同:
function MyClass() {};
var x = new MyClass;
x.toString(); // prints "[object Object]"
MyClass.prototype.toString = function() { return 'hello!' }
x.toString(); // prints "hello!"
// and we can call Object's toString method instead
Object.prototype.toString.call(x); // prints "[object Object]"
第一个调用调用了Object.prototype.toString,因为MyClass 是Object 的子类并且没有自己的toString 方法。然后当我们给MyClass一个toString方法时,调用x.toString使用MyClass上的toString方法,最后我们可以再次使用Object.prototype.toString.call(x)调用我们的“超类”toString方法。
(typeof this)[0] 有什么作用? (typeof this) 返回您的班级名称。 typeof "" 返回 "string",typeof 5 返回 "number" 等等(注意,数组实际上有 object 类型,而 [] instanceof Array 是真的!)。但是,这始终是小写的。 Object.prototype.toString 返回一个字符串,例如"Object String",其中对象的类型为大写。 (typeof this)[0] 说 “给我字符串的第一个字符”,(typeof this).substr(1) 说 “给我字符串第一个字符以外的每个字符”。同样,这里的字符串(typeof this) 只是对象的小写表示。 toUpperCase 调用确保第一个字符大写。