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
Become a member
to unlock all features

Level Up!

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


    Determine an Object's Constructor with JavaScripts instanceof Operator

    Tyler ClarkTyler Clark

    The instanceof operator can be used to figure out which function created an object. However it does have its drawbacks, such as returning false results. In this lesson we'll understand how the instanceof method determines which function created an object and manipulate the results.



    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




    Instructor: Let's create a function called car that takes an argument of make. We'll say this.make = make. We'll do const myCar = new car, passing in a string of "Ford." Then we'll console.log myCar as an instance of car. We see that we get true from this console.log.

    The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of our object. All instanceof is doing is checking all the prototype object's .constructor properties on our myCar object to see if any of them points to the car function.

    If we create another function called boat that took an argument of engine and said this.engine = engine, then we did Object.setPrototypeOf our boat.prototype object with the car.prototype object, then instead of newing up car, we instead newed up boat for our myCar, you can see that our instanceof still is true.

    This might seem strange because our myCar object seems to really be an instance of boat and not car. Because we delegated the next-in-line prototype chain object of boat's prototype to be car's prototype, our instanceof finds the car function and returns true.

    If we quickly refactored our functions into classes, we could see that this doesn't change anything. We'd still get a true back from using the instanceof on our new instance of boat.