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)); // 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)); // null