简体   繁体   English

Object.create(父级)vs Object.create(父级原型)

[英]Object.create(parent) vs Object.create(parent.prototype)

My question is about inheritance in javascript. 我的问题是关于javascript中的继承。 So when you have 所以当你有

child.prototype = Object.create(parent.prototype) 

you are setting the prototype of the child class to a copy of the parent class prototype. 您正在将子类的原型设置为父类原型的副本。 If you check in the console the __proto__ property of the child class shows directly __proto__: parent . 如果您在控制台中签入,则子类的__proto__属性直接显示__proto__: parent So far so good. 到现在为止还挺好。 But when you make inheritance like that - 但是当您这样继承时-

child.prototype = Object.create(parent) 

the __proto__ property of child shows __proto__: function parent() and this function has property prototype which has key-value prototype: parent . child的__proto__属性显示__proto__: function parent() ,此函数具有属性原型,该原型具有键值prototype: parent The instances of both act the same. 两者的实例作用相同。 Obviously the compiler should take only 1 step more to find the functions in the prototype. 显然,编译器只需要多执行一步就可以找到原型中的函数。 There is some kind of difference but is it so significant so Object.create(parent.prototype) is preferred. 虽然存在某种差异,但差异非常大,因此首选Object.create(parent.prototype) Can anyone explain this in simple terms? 谁能用简单的术语解释一下?

One of the most confusing pitfalls in javascript is that .prototype and "prototype" are different things. javascript中最令人困惑的陷阱之一是.prototype和“ prototype”是不同的东西。 In your example, properties of the first object are resolved via parent.prototype , while the second uses "parent's prototype" aka parent.__proto__ . 在您的示例中,第一个对象的属性是通过parent.prototype解析的,而第二个对象则是使用“父母的原型”,也称为parent.__proto__ Consider: 考虑:

function parent() {};

var a = Object.create(parent.prototype); 
var b = Object.create(parent);

This is the inheritance diagram for this code: 这是此代码的继承图:

在此处输入图片说明

As you can see, prototype chains for a and b are quite different. 如您所见, ab原型链非常不同。

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

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