var d = [];
console.log(typeof d); // weird!
console.log(d.toString()); //Prints nothing since there are no elements in the array
console.log(Object.prototype.toString.call(d)); // better!
当我运行上面的代码时,第一个 console.log 打印对象,这是预期的,因为数组是一个对象,第二个 console.log 打印 [object Array]。我对 Object.prototype.toString.call(d)
的工作原理有点困惑。
所以我知道数组原型(prototype)上的 toString 方法只是尝试打印出数组内部的元素。但是,当您在基础对象的原型(prototype)上调用 toString 方法时,该 toString 方法到底做了什么?它是否也尝试打印出数组的元素?基础 Object 上的 toString 方法是否也使用关键字 cái này
,因为我们使用的是 .call
,它会在调用函数时更改 this 关键字指向的内容。
您可以将 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()
不同,因为数组只是一个对象的子对象,数组的
只是被覆盖了:
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
bởi vì Lớp học của tôi
Đúng Object
的子类并且没有自己的
方法。然后当我们给 Lớp học của tôi
một
方法时,调用 x.toString
sử dụng MyClass 上的
方法
,最后我们可以再次使用 Object.prototype.toString.call(x)
调用我们的“父类(super class)”
方法。
(typeof this)[0] 做什么? (typeof this)
返回您的类的名称。 typeof ""
trở lại "string"
,typeof 5
trở lại "number"
,等等(注意,数组实际上有键入 object
,但 [] instanceof Array
为真!)。但是,这始终是小写的。 Object.prototype.toString
返回一个字符串,例如 "Object String"
,其中对象的类型为大写。 (typeof this)[0]
说 “给我字符串的第一个字符”,和 (typeof this).substr(1)
说 “给我字符串第一个字符以外的每个字符”。同样,此处的字符串 (typeof this)
只是对象的小写表示。 toUpperCase
调用确保第一个字符大写。
Tôi là một lập trình viên xuất sắc, rất giỏi!