简体   繁体   中英

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. I am calling halogen.read() it is getting read property but halogen is prototype for balloon but balloon is not prototype of halogen. How js is working under the hood??

 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. 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.

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:

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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