Object.prototype.toString.call(arrayObj)和arrayObj.toString()之间的区别 [英] Difference between Object.prototype.toString.call(arrayObj) and arrayObj.toString()
问题描述
我已经阅读了一些材料,并且在语法方面没有完全掌握这个概念,如下所示:
I have gone through some materials and haven't completely grasped the concept when it comes to syntax such as the following :
var arrObj = [1,2,3];
Object.prototype.toString.call(arrObj); //Gives "[object Array]"
arrObj.toString(); // Gives "1,2,3"
第2行和第3行有何不同?据我所知,两者都调用toString方法,当前对象设置为'arrObj'。
How are the lines 2 and 3 different? As far as I understood, both call the toString method with current object being set to 'arrObj'.
推荐答案
自 toString
在 Object.prototype
中定义,无论谁继承 Object
,都将通过默认获取 toString
方法。
Since toString
is defined in Object.prototype
, whoever inherits Object
, will by default get the toString
method.
但是,数组
对象,覆盖默认的 toString
方法,将数组元素打印为逗号分隔的字符串。
But, Array
objects, override the default toString
method to print the array elements as comma separated string.
Object.prototype.toString
不知道它实际处理的Object类型。因此,它有意保持通用,并始终打印对象的实际类型。这就是为什么
Object.prototype.toString
doesn't know what type of Object it actually deals with. So, it is intentionally kept generic and it always prints the actual type of the Object. That is why
console.log(Object.prototype.toString.call(arrObj));
打印
[object Array]
这是对象的类型通过。但是,当你执行 arrObj.toString
时,你试图用它的String形式表示数组,所以 toString
是覆盖数组
对象,以逗号分隔的字符串形式打印数组元素。
which is the type of object passed. But, when you do arrObj.toString
, you are trying to represent the array in its String form, so toString
is overriden in Array
objects to print the array elements as comma separated string.
这就是两个调用不同的原因。
That is why both the calls are different.
但是对于其他对象, toString
是没有覆盖,所以他们将使用 Object.prototype.toString
中的 toString
。例如,
But in case of other objects, the toString
is not overriden, so they will use the toString
from the Object.prototype.toString
. For example,
var obj = {
1: 2
};
console.log(obj.toString());
// [object Object]
阅读MDN的 Overriding the默认 toString
方法
这篇关于Object.prototype.toString.call(arrayObj)和arrayObj.toString()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!