DEV Community

Discussion on: What is Polymorphism? - Explaining Polymorphism to a Five Year Old

Collapse
machineno15 profile image
Tanvir Shaikh • Edited on

i understood some part of this, can you please explain me what's happening here ? that will be helpful

Collapse
lukeshiru profile image
LUKESHIRU • Edited on

Sure!

  • First: createAircraft takes a single argument, which is an object with the values, but you can pass some and omit others, or omit them all and leave the defaults if you want. The good thing about it being an object, is that you can easily skip some arguments, or use whatever order you prefer, and it still works. Adding new arguments is a piece of cake as well.
createAircraft(); // Leaving all the defaults valid
createAircraft({ wings: 1 }); // Setting only 1 property valid as well
createAircraft(({ wings = 1, engines = 1, wheels = 4 }); // Setting all properties... valid!
Enter fullscreen mode Exit fullscreen mode
  • Second: Because createAircraft returns an object with some functions in it, you can create new objects from it, so when createHelicopter does { ...aircraft }, is adding all the functions returned by createAircraft to its own output object, and then some more (propel and lift).
  • Third: This example could be way more simple if the functions were outside of createAircraft, but the idea was to show that you can "replicate" what you can do with classes, without them.
  • Forth: Ideally, every method should actually return the string instead of logging it, but I tried to replicate the original example.

Bonus: Here's how you can use the code above, and what's the output:

createAircraft();
/*
Returns:
{
    start: () => console.log(`turning on my 2 engines!`),
    stand: () => console.log(`standing on my 3 tires!`),
    run: () => console.log(`moving down the runway on my 3 tires!`),
    fly: () => console.log(`soaring the sky on my 2 wings!`)
}
*/
createHelicopter({ propellers: 2 });
/*
Returns:
{
    start: () => console.log(`turning on my 2 engines!`),
    stand: () => console.log(`standing on my 3 tires!`),
    run: () => console.log(`moving down the runway on my 3 tires!`),
    fly: () => console.log(`soaring the sky on my 2 wings!`),
    propel: () => console.log(`spinning my 2 propellers!`),
    lift: () => {
        aircraft.stand(); // Will log `turning on my 2 engines!`
        aircraft.start(); // Will log `standing on my 3 tires!`
        propel(); // Will log `spinning my 2 propellers!`
        console.log("slowly climbing up thanks to my spinning propellers!");
    };
}
*/
Enter fullscreen mode Exit fullscreen mode

Let me know if there is something else I can help you with :D