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

    Understanding the .constructor property on JavaScript Objects

    Tyler ClarkTyler Clark
    javascriptJavaScript

    Constructor functions hold an interesting purpose in JavaScript. Unlike in classical languages, they do not always mean created by. In this lesson we’ll use the new keyword to make a constructor call and work with the .constructor property.

    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 When functions are declared, they are automatically given a property of prototype that has a value of an object. By default, this object just has one accessible property, the .constructor property, which will point back to the memory reference location of the function the prototype object was created with.

    00:18 In our case, that's this foo function. With that in mind, if we do const a equals new foo, and then console.log a.constructor as equal to foo, we get true. This constructor property does not live on the newly created object from our new keyword here to our variable a.

    00:36 It's going through the prototype chain and finding this value here, that lives on the prototype object of foo. Because of this relationship between the new object created from the new keyword and the foo function, it might be easy to assume that .constructor will always reference the function that created it.

    00:55 However, this is not true. We can reassign the prototype to a new object. By doing this mutation, our constructor property will return the global object constructor function. Even though our variable a is still created with the new keyword against the foo function, our two values are no longer equal.

    01:15 We can get a true value if we equal on the global object constructor. We can play with this even more by doing object.defineProperty, foo.prototype, constructor, and then enumerable false, writable true, configurable true, and value of foo.

    01:36 Now, if we look back at our values, we can see that the .constructor property in both cases is back to referencing the foo function, even though we're completely reassigning the foo prototype object to be just this anonymous object.

    Discuss

    Discuss