Prototypal inheritance
suggest changeSuppose we have a plain object called prototype:
const 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
const 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 follows object references, and those objects are mutable. Changing a prototype property is visible immediately on every object that still inherits it. An own property of the same name on the child hides the prototype property.
prototype.foo = "bar";
console.log(obj.foo);
Console output
"bar"
Most objects inherit from Object.prototype through their prototype chain. Object.create(null) does not. Adding properties to Object.prototype is visible to ordinary objects, and it breaks code that assumes those names are absent, especially when a library is involved. The next example does that on purpose:
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.