简体   繁体   English

原型 inheritance 如何以相反的顺序工作

[英]How Prototypal inheritance works in reverse order

As you can see below is my code.如您所见,下面是我的代码。 I have created two objects halogen and balloon and given halogen property of sing and balloon property of read.我创建了两个对象halogen 和 balloon,并给出了sing 的halogen 属性和read 的balloon 属性。 I am calling halogen.read() it is getting read property but halogen is prototype for balloon but balloon is not prototype of halogen.我正在调用halogen.read() 它正在读取属性,但卤素是气球的原型,但气球不是卤素的原型。 How js is working under the hood?? js是如何在幕后工作的?

 const halogen = { sing: function() { console.log('I can sing'); } } const balloon = new Object(halogen); balloon.read = function() { console.log('I can read'); } halogen.read();

When you call the Object constructor with an argument that isn't null or undefined , it doesn't create a new object (not even when you use new , surprisingly; spec link ), it just converts the argument to object if it isn't already an object and returns it. When you call the Object constructor with an argument that isn't null or undefined , it doesn't create a new object (not even when you use new , surprisingly; spec link ), it just converts the argument to object if it isn' t 已经是 object 并返回它。 Since halogen already refers to an object, there's no conversion required and you're basically doing balloon = halogen and they both end up referring to the same object.由于halogen已经指的是 object,因此不需要转换,您基本上是在做balloon = halogen ,它们最终都指的是同一个object。

You probably meant to use Object.create , which creates a new object and assigns the object argument you provide as the new object's prototype:您可能打算使用Object.create ,它创建一个新的 object 并分配您提供的 object 参数作为新对象的原型:

 const halogen = { sing: function() { console.log("I can sing"); }, }; const balloon = Object.create(halogen); balloon.read = function() { console.log("I can read"); }; console.log(typeof halogen.read); // undefined console.log(typeof balloon.read); // function console.log(typeof balloon.sing); // function

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

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