[英]Clarification: Javascript prototype update confusion
Possible answer , but answer shows what's observed but doesn't explain why it happens that way. 可能的答案 ,但答案显示观察到的内容,但不能解释为什么会这样发生。
Let's create three function constructors. 让我们创建三个函数构造函数。
function A() {
}
function B() {
}
function C() {
}
C.prototype.nm = "C";
B.prototype = new A()
var obj = new B()
B.prototype = new C()
console.log(obj.nm); // prints, undefined.
So after the last line I was expecting 'obj' to receive properties from prototype of C but it's not. 因此,在最后一行之后,我期望'obj'从C原型接收属性,但事实并非如此。 So does it mean that once the object is created it is tied to whatever prototype it was assigned during creation ?
这是否意味着一旦创建了对象,它便会绑定到在创建过程中分配的任何原型? Why is it that way, I mean I can receive live updates to object through the prototype but wouldn't it be better if can get updates from multiple objects just changing constructors prototype property ?
为什么这样,我的意思是我可以通过原型接收对象的实时更新,但是如果仅更改构造函数的原型属性就可以从多个对象获取更新,那不是更好吗?
您没有为B分配任何特定的原型属性,因此继承链断开了。
Does it mean that once the object is created it is tied to whatever prototype it was assigned during creation ?
这是否意味着一旦创建了对象,它就会与创建过程中分配的任何原型绑定在一起?
Yes, exactly. 对,就是这样。 Objects inherit properties from the object in their [[Prototype]] internal property.
对象从其[[Prototype]]内部属性中继承了对象的属性。
That property is set when you create the instance: 创建实例时设置该属性:
But if you change the prototype
property of a constructor, it won't affect previous instances. 但是,如果更改构造函数的
prototype
属性,它将不会影响以前的实例。
In fact, prototype
is not special by itself, it's just that [[Construct]] internal method uses it while creating instances. 实际上,
prototype
本身并不特殊,只是[[Construct]]内部方法在创建实例时使用它。
once the object is created it is tied to whatever prototype it was assigned during creation ?
一旦创建了对象,就将其绑定到在创建过程中分配的任何原型?
Mostly yes. 通常是的。 You can change it, but is not recommended (because of performance issues), using:
您可以使用以下方法进行更改,但不建议这样做(由于性能问题):
__proto__
: this was a non-standard property in Object.prototype
which could be used as a getter or setter of [[Prototype]]. __proto__
:这是Object.prototype
的非标准属性,可以用作[[Prototype]]的获取器或设置器。 ECMAScript 6 standardized it in Annex B (Additional ECMAScript Features for Web Browsers). ECMAScript的6 标准化的IT附件B(附加功能的ECMAScript为Web浏览器)。
Object.setPrototypeOf
, a new method introduced by ECMAScript 6. Object.setPrototypeOf
,这是ECMAScript 6引入的新方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.