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();
}

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay