Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

    Replicate JavaScript Constructor Inheritance with Simple Objects (OLOO)

    Tyler ClarkTyler Clark
    javascriptJavaScript

    Do you get lost when working with functions and the new keyword? Prototypal inheritance can be completely replicated without either of those two concepts. In this lesson we will convert an object created from the new keyword against a function, to simply objects linked to other objects.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    Instructor: 00:00 If you find yourself using the new keyword a lot with functions...For example, if you did function House takes an argument of color, this.color = color. Then you did const myHouse = new House, passing in a string of "white." Then if we console.logged myHouse.color, we'd get "white."

    00:20 This probably accomplishes what you're trying to get in the end but might not be the best option. The new keyword not only calls a function but returns a new object, points the this context, and links prototypes.

    00:31 We could go about this in a different manner that is a little bit more straightforward. Instead, we can change this function to just be a regular object called House. We'll move the this.color assignment into a setter function called houseColor.

    00:44 We can change how the myHouse object's created. Instead of the new keyword, let's just use Object.create, passing through House. When we use this.colorLookup, we can pass through white. Then we see that myHouse object now has a property of color white.

    01:03 Our end result is the same. We didn't have worry about creating a function and calling it with the new keyword. This pattern is called OLOO, or objects linking to other objects.

    01:14 Since prototypes are simply objects, objects can be created in a manner so that they're easily delegated as prototypes of other objects. Object.create gives us the ability to easily create new objects that have specifically delegated prototype objects.

    Discuss

    Discuss