Skip to content

Instantly share code, notes, and snippets.

@sharmaeklavya2
Created July 21, 2018 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sharmaeklavya2/20097562f93ef15bb930bfa4439d301a to your computer and use it in GitHub Desktop.
Save sharmaeklavya2/20097562f93ef15bb930bfa4439d301a to your computer and use it in GitHub Desktop.
JS class notes

JavaScript object hierarchy

This document aims to explain what various attributes like constructor, prototype and __proto__ point to and what happens when new objects are created.

There are several ways of creating new objects:

  • o = {'one': 1, 'two': 2};
  • function f() {return 'three';}
  • ford = new Car('Ford');
  • o2 = Object.create(o);

We will see what each of these statements do.

Object and Function

The following statements evaluate to true:

typeof(Object) === 'function'
typeof(Function) === 'function'
typeof(Object.prototype) === 'object'
typeof(Function.prototype) === 'function'

Every object has the properties constructor and __proto__ which it inherits from Object.prototype. Additionally, every function (except Function.prototype) has its own property prototype.

The following statements evaluate to true:

Object.constructor === Function
Object.__proto__ === Function.prototype

Object.prototype.constructor === Object
Object.prototype.__proto__ === null

Function.constructor === Function
Function.__proto__ === Function.prototype

Function.prototype.constructor === Function
Function.prototype.__proto__ === Object.prototype

Object literal

o = {'1': 'one', '2': 'two'};
typeof(o) === 'object'
o.constructor === Object
o.__proto__ === Object.prototype

Function definition

function f() {return 'three';}
typeof(f) === 'function'
f.constructor === Function
f.__proto__ === Function.prototype

typeof(f.prototype) === 'object'
f.prototype.constructor === f
f.prototype.__proto__ === Object.prototype

Creating an object using constructor

When creating an object using new constructor_name(params);, a copy of constructor_name.prototype is created and constructor_name gets applied to it.

function Car(name) {
    this.name = name;
}
Car.prototype.wheels = true;

ford = new Car('Ford');
ford.model = 'Figo';
ford.hasOwnProperty('name')
ford.constructor === Car
ford.__proto___ === Car.prototoype

Creating an object using Object.create

o2 = Object.create(o);
o2.three = 3;
o2.constructor === Object
o2.__proto__ == o
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment