Geek Culture
Published in

Geek Culture

All about inheritance in javascript

Apple objects get their water from the root object. Image by Jen Theodore.
The keyword “new” calls a function as a constructor

All objects in Javascript are created by constructors

declaring a “regular” javascript object
Curly braces are shorthand for new Object({})
const myStr = "Hello!";
console.log(myStr.toUpperCase()); // HELLO!
Javascript wraps primitives in temporary objects when needed

How is a constructor different from a function?

proof that “this” variable inside the constructor points to the returned object by “new”

Prototype

person.__proto__.constructor === PersonConstructor; // true

What is __proto__ property anyway?

An object’s __proto__ property points to the “prototype" property on the constructor of that object.

the usage of object’s __proto__ property
PersonConstructor.prototype.__proto__
prototype chain
proof of prototype chain

Wrapping Up

  • Constructors are functions, called with new keyword.
  • All Javascript objects are created by constructors.
  • The new keyword, creates an empty plain object and passes it to the constructor function as a variable called this.
  • If the constructor function doesn’t return an object, this will be returned implicitly.
  • The “regular” or “plain” object is created by the built-in Object constructor.
  • objects are aware of their constructor through a property called __proto__.
  • Property __proto__ on each object, points to its constructor’s prototype property.
  • prototype property exists on all javascript functions. By default, it is a plain object having only one property called constructor which points to the constructor function itself.
  • prototype property is just another object, it means that it has a __proto__ property too. So for a regular function, the constructor of its prototype property is Object.
  • If we want to access a property/method on an object which is missing on the object itself, Javascript looks at the __proto__ of the object (which is the prototype property of its constructor) and if it doesn’t also exist there, the same lookup is done for the __proto__ of the prototype object recursively until it either finds it or reaches null and returns undefined. This is called the “Prototype Chain”.
  • Since the property __proto__ on all instances of the constructor functions point to its prototype property, mutating prototype property on the constructor function is immediately available on all instances.

--

--

A new tech publication by Start it up (https://medium.com/swlh).

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store