Understanding the .constructor property on JavaScript Objects

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 5 years ago

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.

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.

Juan Jose
Juan Jose
~ 6 years ago

Hi , In the last code, the last line console.log(a.constructor === Object ) // true should be // false. Amazing video!.

Brendan Whiting
Brendan Whiting
~ 5 years ago

I don't understand where it says that console.log(Foo.prototype.constructor) prints [λ: Foo]. I'm using this playground and it prints function Foo() {}. Where does that lamdba symbol come from?

Jake
Jake
~ 5 years ago

Don't understand...

David Choi
David Choi
~ 5 years ago

Tyler your last example uses Object.defineProperty to reset Foo.prototype's constructor to an anonymous object. And yet when you later call console.log(a.constructor === Foo) it returns true. Why is it Foo and not Object if I created an anonymous object?

Markdown supported.
Become a member to join the discussionEnroll Today