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 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.
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)); // nullJavaScript 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); // greenUse the standard Object.getPrototypeOf() method.
const shared = {};
const child = Object.create(shared);
console.log(Object.getPrototypeOf(child) === shared); // trueUse 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')); // falseThe 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')); // falseCall 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)); // nullPass a property descriptor map as the second argument to Object.create() to define own properties immediately.
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.
const base = { ready: true };
const app = Object.create(base);
console.log(app.missing); // undefined