Prototypes & Inheritance in JavaScript - Exercise 1

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

javascript

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

Pass the desired prototype object to Object.create() to create an object whose property lookup delegates to that prototype. The new object starts without copied own properties, so later changes to the prototype may be visible through it.

javascript

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.

javascript

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.

javascript

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

Use the standard Object.getPrototypeOf() method.

javascript

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.

javascript

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.

javascript

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.

javascript

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

Pass a property descriptor map as the second argument to Object.create() to define own properties immediately.

javascript

const prototype = { active: true };
const record = Object.create(prototype, {
  name: { value: 'Ava', enumerable: true }
});
console.log(record.name, record.active);

The lookup returns undefined when no object in the chain contains the requested property.

javascript

const base = { ready: true };
const app = Object.create(base);
console.log(app.missing); // undefined
All sections expanded. Activate the control to collapse all sections.