JavaScript TutorialDatatypes in JavaScriptEvaluating JavaScriptFunctional JavaScriptJavaScript .postMessage() and MessageEventJavaScript AJAXJavaScript Anti-patternsJavaScript Arithmetic (Math)JavaScript ArraysJavaScript Arrow FunctionsJavaScript Async functions (async/await)JavaScript Async IteratorsJavaScript Automatic Semicolon Insertion - ASIJavaScript Battery Status APIJavaScript Behavioral Design PatternsJavaScript Binary DataJavaScript Bitwise operatorsJavaScript Bitwise Operators - Real World Examples (snippets)JavaScript BOM (Browser Object Model)JavaScript Built-in ConstantsJavaScript CallbacksJavaScript ClassesJavaScript CommentsJavaScript Comparison OperationsJavaScript ConditionsJavaScript ConsoleJavaScript Constructor functionsJavaScript Context (this)JavaScript CookiesJavaScript Creational Design PatternsJavaScript Custom ElementsJavaScript Data attributesJavaScript Data ManipulationJavaScript DateJavaScript Date ComparisonJavaScript DebuggingJavaScript Declarations and AssignmentsJavaScript Destructuring assignmentJavaScript Detecting browserJavaScript EnumerationsJavaScript Error HandlingJavaScript Escape SequencesJavaScript EventsJavaScript execCommand and contenteditableJavaScript FetchJavaScript File API, Blobs and FileReadersJavaScript Fluent APIJavaScript FunctionsJavaScript GeneratorsJavaScript GeolocationJavaScript Global error handling in browsersJavaScript HistoryJavaScript How to make iterator usable inside async callback functionJavaScript IndexedDBJavaScript InheritanceJavaScript Intervals and TimeoutsJavaScript JSONJavaScript Linters - Ensuring code qualityJavaScript LocalizationJavaScript LoopsJavaScript MapJavaScript Memory efficiencyJavaScript Method ChainingJavaScript Modals - PromptsJavaScript Modularization TechniquesJavaScript ModulesJavaScript NamespacingJavaScript Navigator ObjectJavaScript Notifications APIJavaScript ObjectsJavaScript Performance TipsJavaScript PromisesJavaScript Prototypes, objectsJavaScript ProxyJavaScript Regular expressionsJavaScript requestAnimationFrameJavaScript Reserved KeywordsJavaScript Same Origin Policy & Cross-Origin CommunicationJavaScript ScopeJavaScript ScreenJavaScript Security issuesJavaScript Selection APIJavaScript Server-sent eventsJavaScript SetJavaScript Setters and GettersJavaScript Strict modeJavaScript StringsJavaScript SymbolsJavaScript Tail Call OptimizationJavaScript Template Literals

JavaScript Inheritance

From WikiOD

Standard function prototype[edit | edit source]

Start by defining a Foo function that we'll use as a constructor.

function Foo (){}

By editing Foo.prototype, we can define properties and methods that will be shared by all instances of Foo. = function() {
  return 'I am bar';

We can then create an instance using the new keyword, and call the method.

var foo = new Foo();

console.log(; // logs `I am bar`

Difference between Object.key and Object.prototype.key[edit | edit source]

Unlike in languages like Python, static properties of the constructor function are not inherited to instances. Instances only inherit from their prototype, which inherits from the parent type's prototype. Static properties are never inherited.

function Foo() {}; = 'bold';

var foo = new Foo();

console.log(; // 'bold'
console.log(; // undefined = 'italic';

console.log(; // 'bold'
console.log(; // 'italic'

Prototypal inheritance[edit | edit source]

Suppose we have a plain object called prototype:

var prototype = { foo: 'foo', bar: function () { return; } };

Now we want another object called obj that inherits from prototype, which is the same as saying that prototype is the prototype of obj

var obj = Object.create(prototype);

Now all the properties and methods from prototype will be available to obj


Console output


Prototypal inheritance is made through object references internally and objects are completely mutable. This means any change you make on a prototype will immediately affect every other object that prototype is prototype of. = "bar";

Console output


Object.prototype is the prototype of every object, so it's strongly recommended you don't mess with it, specially if you use any third party library, but we can play with it a little bit.

Object.prototype.breakingLibraries = 'foo';

Console output


Fun fact I've used the browser console to make these examples and broken this page by adding that breakingLibraries property.

Pseudo-classical inheritance[edit | edit source]

It's an emulation of classical inheritance using prototypical inheritance which shows how powerful prototypes are. It was made to make the language more attractive to programmers coming from other languages.


IMPORTANT NOTE: Since ES6 it doesn't make sense to use pseudo-calssical inheritance since the language simulates conventional classes. If you're not using ES6, you should. If you still want to use the classical inheritance pattern and you're in a ECMAScript 5 or lower environment, then pseudo-classical is your best bet.

A "class" is just a function that is made to be called with the new operand and it's used as a constructor.

function Foo(id, name) { = id; = name;

var foo = new Foo(1, 'foo');

Console output


foo is an instance of Foo.The JavaScript coding convention says if a function begins with a capital letter case it can be called as a constructor (with the new operand).

To add properties or methods to the "class" you have to add them to it's prototype, which can be found in the prototype property of the constructor. = 'bar';

Console output


In fact what Foo is doing as a "constructor" is just creating objects with Foo.prototype as it's prototype.

You can find a reference to its constructor on every object


function Foo(id, name) { ...

console.log({ }.constructor);

function Object() { [native code] }

And also check if an object is an instance of a given class with the instanceof operator

console.log(foo instanceof Foo);


console.log(foo instaceof Object);


Setting an Object's prototype[edit | edit source]


With ES5+, the Object.create function can be used to create an Object with any other Object as it's prototype.

const anyObj = {
    hello() {
        console.log(` is ${}`);

let objWithProto = Object.create(anyObj); = 'bar';

objWithProto.hello(); // " is bar"

To explicitly create an Object without a prototype, use null as the prototype. This means the Object will not inherit from Object.prototype either and is useful for Objects used for existence checking dictionaries, e.g.

let objInheritingObject = {};
let objInheritingNull = Object.create(null);

'toString' in objInheritingObject; // true
'toString' in objInheritingNull ; // false


From ES6, the prototype of an existing Object can be changed using Object.setPrototypeOf, for example

let obj = Object.create({foo: 'foo'});
obj = Object.setPrototypeOf(obj, {bar: 'bar'});; // undefined; // "bar"

This can be done almost anywhere, including on a this object or in a constructor.

Note: This process is very slow in current browsers and should be used sparingly, try to create the Object with the desired prototype instead.


Before ES5, the only way to create an Object with a manually defined prototype was to construct it with new, for example

var proto = {fizz: 'buzz'};

function ConstructMyObj() {}
ConstructMyObj.prototype = proto;

var objWithProto = new ConstructMyObj();
objWithProto.fizz; // "buzz"

This behaviour is close enough to Object.create that it is possible to write a polyfill.

New object from prototype[edit | edit source]

In JavaScript, any object can be the prototype of another. When an object is created as a prototype of another, it will inherit all of its parent's properties.

var proto = { foo: "foo", bar: () => };

var obj = Object.create(proto);


Console output:

> "foo"
> "foo"

NOTE Object.create is available from ECMAScript 5, but here's a polyfill if you need support for ECMAScript 3

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();



The Object.create() method creates a new object with the specified prototype object and properties.

Syntax: Object.create(proto[, propertiesObject])


  • proto (The object which should be the prototype of the newly-created object.)
  • propertiesObject (Optional. If specified and not undefined, an object whose enumerable own properties (that is, those properties defined upon itself and not enumerable properties along its prototype chain) specify property descriptors to be added to the newly-created object, with the corresponding property names. These properties correspond to the second argument of Object.defineProperties().)

Return value

A new object with the specified prototype object and properties.


A TypeError exception if the proto parameter isn't null or an object.