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
Autoplay

    Determine an Object's Constructor with JavaScripts instanceof Operator

    Tyler ClarkTyler Clark
    javascriptJavaScript

    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.

    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 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.

    00:18 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.

    00:38 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.

    01:00 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.

    01:19 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.

    Discuss

    Discuss