JavaScript: Understanding Prototype & Inheritance

, , …,
Want to master JavaScript in a week? Buy Xah JavaScript Tutorial.

This page is a tutorial of JavaScript's object, inheritance, prototype.

Every JavaScript object O has a prototype attribute (aka “internal property”). ECMAScript §4#sec-4.3.5 The value of the prototype attribute is some object P. (or null).

The object P is called the “prototype object” of O. (we'll call it “parent object”.)

When a property is accessed, JavaScript will look for the property in the object, if none found, it'll look at its parent, then parent of parent, etc, till the property is found or root object is reached. This is inheritance.

The parent object has its own parent, thus we have what's called a prototype chain. (the prototype chain is never circular.) ECMAScript §8#sec-8.6.2

How to Find a Object's Prototype/Parent?

2 methods you can use to check parent object.

  1. Object.getPrototypeOf(obj)
  2. a.isPrototypeOf(b)

See: JavaScript: How to Find Object's Prototype/Parent?

How to Create Object with Specified Parent?

2 ways to create a object with a specified prototype.

  1. Object.Create(obj)
  2. Use a constructor function F and set F.prototype.

See: JavaScript: How to Create Object with Specified Parent?

Root of All Objects is 「Object.prototype」

The root of all JavaScript objects is Object.prototype. Itself doesn't have any parent. Its prototype is null.

Object.getPrototypeOf(Object.prototype) === null // true

What's Parent of User Created Objects

Parent of 「{…}」

A object created by literal expression {…} has parent that's the value of Object.prototype.

Object.getPrototypeOf({}) === Object.prototype // true

Parent of Object Created by Constructor Function

The parent of object created by new F(…) is:

// example of inheritance by constructor

var o1 = {};
var FF = function () { };
FF["prototype"] = o1;
var o2 = new FF();

console.log( Object.getPrototypeOf(o2) === o1 ); // true

Another example, using the default constructor function Date:

// example of inheritance by constructor
var dd = new Date();
console.log( Object.getPrototypeOf(dd) === Date["prototype"]); // true

〔➤ JavaScript: What's Constructor? What Does Keyword “new” Do?

blog comments powered by Disqus