Prototypes & Inheritance in JavaScript - Exercise 1

A prototype is an object that another object can delegate property and method lookups to.

const animal = {
  speak() { return 'sound'; }
};
const dog = Object.create(animal);
console.log(dog.speak());

Pass the prototype object to Object.create().

const defaults = { theme: 'light' };
const settings = Object.create(defaults);
console.log(settings.theme);

It is the sequence of linked prototypes JavaScript searches until it reaches null.

const item = {};
console.log(Object.getPrototypeOf(item) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype)); // null

JavaScript uses the object's own property first, so it hides the value found on the prototype.

const defaults = { color: 'blue' };
const button = Object.create(defaults);
button.color = 'green';
console.log(button.color); // green

Use the standard Object.getPrototypeOf() method.

const shared = {};
const child = Object.create(shared);
console.log(Object.getPrototypeOf(child) === shared); // true

Use Object.hasOwn() to exclude properties inherited from the prototype chain.

const proto = { inherited: true };
const value = Object.create(proto);
value.own = true;
console.log(Object.hasOwn(value, 'own')); // true
console.log(Object.hasOwn(value, 'inherited')); // false

The in operator checks both own properties and inherited properties.

const proto = { ready: true };
const app = Object.create(proto);
console.log('ready' in app); // true
console.log(Object.hasOwn(app, 'ready')); // false

Call Object.create(null) when you need a clean dictionary without inherited properties.

const dictionary = Object.create(null);
dictionary.key = 'value';
console.log(Object.getPrototypeOf(dictionary)); // null