简体   繁体   English

Javascript Prototype继承和Object.create()?

[英]Javascript Prototype Inheritance and Object.create()?

There is something confusing me about prototypes in JS. JS中的原型让我感到困惑。

Let's suppose I have an object like this : 假设我有一个像这样的对象:

 let a = { b: 1 }; 

Now, I want to create another object which inherits of the properties of 'a'. 现在,我想创建另一个继承“a”属性的对象。

 let obj = Object.create(a); 

So in this situation, I will link the proto of my 'obj' to the proto of 'a' which will link to the Object.prototype. 所以在这种情况下,我将我的“OBJ”的链接到“A”,将链接到Object.prototype中的原型 The first question is, does it remove the link of obj. 第一个问题是,它是否删除了obj的链接。 proto to replace by the a. 原型由a取代。 proto ? 原型

Now let's suppose I do: 现在让我们假设:

 a = 2; 

I would think it updates 'a' in memory removing his references. 我认为它会在内存中更新“a”,删除他的引用。

So now if I do : 所以现在如果我这样做:

 a.isPrototypeOf(obj) 

It logically returns false . 它在逻辑上返回false But weirdly 'obj' still point to the property b and can access it(obj.b print 1). 但奇怪的是'obj'仍然指向属性b并且可以访问它(obj.b print 1)。 What is the mecanism beyond that ? 除此之外还有什么机制?

Technically, when you replace an object with another one new value, the object's old reference will be cut off from the variable. 从技术上讲,当您用另一个新值替换一个对象时,该对象的旧引用将从该变量中切除。 But it will be still alive until the linked variable dies. 但是在链接变量消失之前它仍然存在。

var x = { a:10 }
var y = { x };
x = 10;

Now, everyone would think that, y will carry the value 10 with the property x . 现在,每个人都会认为,y将带有属性x的值10。 But that's not, as i said above the x's older memory location will be stay alive until y garbage collected. 但事实并非如此,正如我上面说的那样,x的旧内存位置将保持活跃状态​​,直到收集垃圾为止。 At the same time, the x would get assigned with newer memory location for the newer value. 同时,x将为较新的值分配较新的内存位置。

So in your case, you are just losing the reference of a by replacing some other value. 所以你的情况,你只是失去的参考a通过更换一些其他的价值。 Hence you cannot use isPrototypeOf(obj) anywhere after replacing the value of a . 因此,你不能使用isPrototypeOf(obj)替换的值之后的任何地方a

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

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