Complete the code to create an object that inherits from another object using __proto__.
const parent = { greet() { return 'Hello'; } };
const child = { __proto__: [1] };
console.log(child.greet());The __proto__ property sets the prototype of the object. Setting it to parent makes child inherit from parent.
Complete the code to check if child inherits the greet method from parent.
const parent = { greet() { return 'Hi'; } };
const child = { __proto__: parent };
console.log('[1]' in child);The in operator checks if a property exists in the object or its prototype chain. Here, 'greet' is the method inherited by child.
Fix the error in the code to properly set the prototype of child to parent using Object.setPrototypeOf.
const parent = { speak() { return 'Hey'; } };
const child = {};
Object.setPrototypeOf(child, [1]);
console.log(child.speak());Object.setPrototypeOf sets the prototype of the first argument to the second. Here, child should inherit from parent.
Fill both blanks to create a prototype chain where child inherits from parent and parent inherits from grandparent.
const grandparent = { say() { return 'Hello from grandparent'; } };
const parent = { __proto__: [1] };
const child = { __proto__: [2] };
console.log(child.say());Setting parent.__proto__ to grandparent and child.__proto__ to parent creates a chain where child inherits from parent, which inherits from grandparent.
Fill all three blanks to create a function constructor Person, add a method to its prototype, and create an instance that uses that method.
function [1](name) { this.name = name; } [2].prototype.sayName = function() { return `My name is ${this.name}`; }; const person = new [3]('Alice'); console.log(person.sayName());
The function constructor is named Person. We add sayName to Person.prototype. Then we create an instance with new Person('Alice') which inherits the method.