Javascript object constructor and prototype

Every web developer knows javascript does not support classical inheritance, we use prototype of functions and objects to fill that gap. It’s called prototypal inheritance. New version of javascript has implemented classical inheritance may be a keyword “class” but actually it’s just a simulation. Under the hood it works using prototype. So it would be better to clear our concept about this confusing prototype.

Constructor function

Let’s declare a function called Shape. And assign some property and value to “this” keyword. At this point “this” keyword points to global object “window”.

Like all other functions, it has a prototype property and it points to Shape{} object, an empty object.

It’s a normal function, But we’ll call it a constructor if we use “new” keyword during invocation.

We invoked/called “Shape” function with “new” keyword. First it creates an empty object. Then “this” keyword in “Shape” points to that new object, populate that new object with the name and value pairs those are associate with “this” keyword. At last “Shape” returns newly created object. So “circle” is our newly created object.

And another important thing happens. The “circle” has an property “__proto__”, this “__proto__” points to Shape.prototype(the empty Shape{} object).

Now if we add properties or methods in Shape.prototype, that will be available for all of objects those are created by “Shape”.

See? the “move” method is not available in “circle” object. But “circle” found it via prototype because its “__proto__” points to Shape.prototype where the “move” method lives.

Why store methods in prototype instead of copying ?

Because this a big memory save. All of objects just need to hold unique properties like x and y. They don’t need to copy all common methods. So we can store tons of common methods in Constructor’s prototype.

Javascript object constructor and prototype

Built in constructors

Javascript has own built in constructor functions like Function, Object, Array, Number, String etc.
This constructors works almost same way like Shape constructor we wrote.

This “str” variable has all of string methods in its prototype. Because it’s __proto__ points to String.prototype. We can also add our custom string method to prototype like this;

This append method is also accessible if string is created by literal syntax, and it is good practice.

An important aside

Constructor functions always returns object. A string created by “String” constructor is actually an object, not a string.

So when you need to check something in your program by strict equality operator it will return false.

So it’s better using literal syntax for primitives, It’s safe and less typing.

Thanks for reading.

MH Rafi

Full stack Javascript developer at ThemEgret