JS-Dev-101 practice question 4 of 25

01 function Animal(size, type) { 02 this.type = type || 'Animal'; 03 this.canTalk = false; 04 } 05 06 Animal.prototype.speak = function() { 07 if…

Full set: 148 questions
01 function Animal(size, type) { 02 this.type = type || 'Animal'; 03 this.canTalk = false; 04 } 05 06 Animal.prototype.speak = function() { 07 if (this.canTalk) { 08 console.log("It spoke!"); 09 } 10 }; 11 12 let Pet = function(size, type, name, owner) { 13 Animal.call(this, size, type); 14 this.size = size; 15 this.name = name; 16 this.owner = owner; 17 } 18 19 Pet.prototype = Object.create(Animal.prototype); 20 let pet1 = new Pet(); Given the code above, which three properties are set for pet1?
Answer options
A: speak
B: owner Correct answer
C: canTalk Correct answer
D: name Correct answer
E: type Correct answer
Correct Answer:
B. owner; C. canTalk; D. name; E. type
Explanation

When new Pet() is called, the Pet constructor executes. It first calls the Animal constructor via Animal.call(this, ...). The Animal constructor sets two "own" properties on the new instance: this.type (to 'Animal', since the argument was undefined) and this.canTalk (to false). Then, the Pet constructor continues and sets the this.name and this.owner properties (both to undefined). Therefore, canTalk, type, name, and owner are all properties set directly on the pet1 instance. The question is flawed as it asks for three properties when four of the options are correct.

Why Incorrect

A. speak is a method inherited via the prototype chain (Pet.prototype which is created from Animal.prototype). It is not an "own" property set directly on the pet1 instance.
Note: The question is flawed as it asks for three properties, but B, C, D, and E are all properties set for the pet1 instance during its construction.

References

1. MDN Web Docs. (2023). new operator. Mozilla. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new. (See section "Description" for the steps of object creation).

2. MDN Web Docs. (2023). Function.prototype.call(). Mozilla. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/GlobalObjects/Function/call. (See section "Using call() to chain constructors for an object").

3. ECMA-262, 13th Edition. (June 2022). ECMAScript® 2022 Language Specification. Section 10.1.13 OrdinaryCreateFromConstructor.

Scroll to Top