0
0
Javascriptprogramming~10 mins

Prototype inheritance in Javascript - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an object that inherits from another object using __proto__.

Javascript
const parent = { greet() { return 'Hello'; } };
const child = { __proto__: [1] };
console.log(child.greet());
Drag options to blanks, or click blank then click option'
Aparent
Bchild
CObject
D{}
Attempts:
3 left
💡 Hint
Common Mistakes
Setting __proto__ to the child itself causes no inheritance.
Using an empty object {} as prototype does not inherit parent's methods.
2fill in blank
medium

Complete the code to check if child inherits the greet method from parent.

Javascript
const parent = { greet() { return 'Hi'; } };
const child = { __proto__: parent };
console.log('[1]' in child);
Drag options to blanks, or click blank then click option'
A'parent'
B'child'
C'greet'
D'hello'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names instead of property names as strings.
Checking for 'parent' or 'child' which are not property names.
3fill in blank
hard

Fix the error in the code to properly set the prototype of child to parent using Object.setPrototypeOf.

Javascript
const parent = { speak() { return 'Hey'; } };
const child = {};
Object.setPrototypeOf(child, [1]);
console.log(child.speak());
Drag options to blanks, or click blank then click option'
Aparent
Bchild
C{}
DObject
Attempts:
3 left
💡 Hint
Common Mistakes
Passing child as the prototype causes no inheritance.
Passing an empty object {} does not link to parent.
4fill in blank
hard

Fill both blanks to create a prototype chain where child inherits from parent and parent inherits from grandparent.

Javascript
const grandparent = { say() { return 'Hello from grandparent'; } };
const parent = { __proto__: [1] };
const child = { __proto__: [2] };
console.log(child.say());
Drag options to blanks, or click blank then click option'
Agrandparent
Bchild
Cparent
D{}
Attempts:
3 left
💡 Hint
Common Mistakes
Reversing the prototype assignments breaks the chain.
Using empty objects {} breaks inheritance.
5fill in blank
hard

Fill all three blanks to create a function constructor Person, add a method to its prototype, and create an instance that uses that method.

Javascript
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());
Drag options to blanks, or click blank then click option'
APerson
DHuman
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for constructor and prototype causes errors.
Adding methods directly to the instance instead of prototype.