简体   繁体   English

将新数组分配给NodeList.prototype

[英]Assigning new Array to NodeList.prototype

Why is not possible to inherit array props and methods when I set NodeList.prototype to Array object like this - NodeList.prototype = new Array; 当我将NodeList.prototype设置为Array object时,为什么不能继承数组Array object和方法NodeList.prototype = new Array; and I can do that with my custom constructor prototype ? 我可以使用我的自定义构造函数原型来做到这一点吗? Why first a object does not inherit array methods and aa does ? 为什么首先a对象不继承阵列的方法和aa呢? Any explanation or blog post link about this is welcome. 欢迎对此进行任何解释或博客文章链接。

function A(a) {
 this.a = a;
}

A.prototype.b = 'b';

var a = new A('a');

A.prototype = new Array; // aa instance will now have map, filter, some ...

var aa = new A('aa');

It doesn't work because the prototype chain is set at construction time. 它不起作用,因为原型链是在构建时设置的。 Calling A.prototype = new Array; 调用A.prototype = new Array; will only affect instances created after that. 只会影响之后创建的实例。

To change the prototype of an object after it has been instantiated, you could use Object.setPrototypeOf(a) 要在实例化对象后更改其原型,可以使用Object.setPrototypeOf(a)

Lastly, note that in your example, you are obliterating the existing prototype so all new instances of A will not have the original b: "b" property. 最后,请注意,在您的示例中,您将消除现有的原型,因此A所有新实例将不具有原始的b: "b"属性。

Changing the prototype of native objects (eg NodeList) is always risky. 更改本机对象(例如NodeList)的原型总是有风险的。 It might or might not work. 它可能会或可能不会。 It's much better to extend the prototype or extend the actual object. 扩展原型或扩展实际对象要好得多。

NodeList.prototype.map = Array.prototype.map;
// or:
someNodeList.map = Array.prototype.map;

And to exaplain you example: When you create a new object, it takes the prototype of the constructor and stores its reference to its __proto__ property. 以示例为例:创建新对象时,它将采用构造函数的原型并将其引用存储到其__proto__属性。 So if you completely replace the prototype of some constructor, it will affect only newly created objects, because they will have a reference to the new prototype. 因此,如果完全替换某些构造函数的原型,它将仅影响新创建的对象,因为它们将引用新的原型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM