DEV Community

Cover image for Objects Making Objects
davidrpolk
davidrpolk

Posted on

4

Objects Making Objects

In this post, I'll be giving a little info on Prototypal Inheritance in JavaScript. Since it's a defining feature of the language, it's kind of important to understand. The examples given here will be kept simple, focusing more on overall concepts.

Constructor Functions


Using a Constructor is probably the most common way of taking advantage of Prototypal Inheritance. In this case, new instances of objects get created using a Constructor, which passes on its Properties to the new instance.

This example uses a pseudoclassical instantiation pattern. It's not the only way to do this same thing, but the concept is the same for functional and class instantiations.

Because of inheritance, if we tried to access a property or method that "bobject" doesn't contain, the lookup gets delegated to "bobject"'s prototype(the object that created "bobject"), in this case, the constructor function "Bob". If "Bob" didn't have the property or method we were looking for, the lookup would get delegated to "Bob"'s prototype, and so on...until the chain ended with finding what we were looking for, or with "null"(which would make the lookup fail).
This delegation has nothing to do with instantiation pattern and constructor functions aren't the only way to take advantage of inheritance.

Object Concatenation

Yes, concatenation isn't just for strings and arrays! It's possible to concatenate objects using "Object.assign()".

As you can see in this example, our newly created object, "bobCat" contains the properties and methods of the objects that created it. Unlike our other example, this one doesn't assign a "constructor"(other than the global Object) to "bobCat".

Closure


It might not seem obvious at first, but using closures is actually a form of inheritance. Since closures are created by a function that is referencing something outside of its own scope, any lookup for that reference will be delegated to the object containing the function!

In conclusion, Prototypal Inheritance is a key feature of JavaScript and should be treated accordingly!

while (life.left.length > 0) {
life.do = coding();
}

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →