JavaScript Prototypal inheritance


Example

Suppose we have a plain object called prototype:

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

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.log(obj.foo);
console.log(obj.bar());

Console output

"foo"
"foo"

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.

prototype.foo = "bar";
console.log(obj.foo);

Console output

"bar"

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.log(obj.breakingLibraries);
console.log(prototype.breakingLibraries);

Console output

"foo"
"foo"

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