Prototype works when declared inside constructor and outside as well

Dear All,

wrt chapter

when I declare prototype inside constructor it works and as well declaring outside of the constructor.

Please clarify why JS doesn’t complain about 2nd scenario or it’s completely valid to declare outside as well ?


Not only is it completely valid, but it makes a whole lot of sense. While constructor’s prototype property can be changed at any point, even inside of said constructor, you generally wouldn’t want to do that. Constructors are usually used to set instance properties, and constructor function’s prototype is modified elsewhere.

Constructors in JS are just regular functions - there is nothing special about them except that they are intended by the programmer to be called with the new operator. It’s the new operator that does all the constructing: it creates a new empty object, links it to the prototype property of your constructor function, points this references inside your constructor call to this new object, and then returns this new object.

Hope that helps.

1 Like

Thanks for detailed clarifications.