gpt4 book ai didi

javascript - 数组原型(prototype) toString() 与对象 toString()

转载 作者:行者123 更新时间:2023-11-30 08:34:03 28 4
gpt4 key购买 nike

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 方法是否也使用关键字 this,因为我们使用的是 .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() 不同,因为数组只是一个对象的子对象,数组的 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 因为 MyClassObject 的子类并且没有自己的 toString 方法。然后当我们给 MyClass 一个 toString 方法时,调用 x.toString 使用 MyClass 上的 toString 方法,最后我们可以再次使用 Object.prototype.toString.call(x) 调用我们的“父类(super class)”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 调用确保第一个字符大写。

关于javascript - 数组原型(prototype) toString() 与对象 toString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33769155/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com