Prototype Chain and Inheritance Quiz
Practice the prototype-chain mechanics: extending built-ins, defining shared properties on `Object.prototype`, and traversing the chain via `Object.getPrototypeOf`.
540 views
8
Augment Array.prototype with a sum() method that returns the sum of the array's numeric elements, then explain one reason this is generally considered an anti-pattern.
Examples
Example 1:
Input: [1, 2, 3, 4].sum()
Output: 10
Explanation: Adding to `Array.prototype` makes the method available on every array literal because of the prototype chain.// add sum() to Array.prototypeAdd a reverse() method to String.prototype that reverses each space-separated word and also reverses the order of the words.
Examples
Example 1:
Input: 'Hello, my name is foo.'.reverse()
Output: '.oof si eman ym ,olleH'
Explanation: Split on spaces, reverse each word, then reverse the word order before joining.// add reverse() to String.prototypeDefine a getLength getter on Object.prototype so that any plain object can answer with its own enumerable key count via obj.getLength().
Examples
Example 1:
Input: ({ a: 1, b: 2, c: { d: 3 }, doSomething: () => {} }).getLength()
Output: 4
Explanation: `Object.keys(this).length` counts only own enumerable string keys, including the function-valued one.// define getLength on Object.prototype as a getter
// expected: obj.getLength() returns Object.keys(obj).lengthWalk up the prototype chain from a class Dog extends Animal instance using Object.getPrototypeOf. Predict what each step prints.
Examples
Example 1:
Input: const d = new Dog(); Object.getPrototypeOf(d) === Dog.prototype; Object.getPrototypeOf(Dog.prototype) === Animal.prototype; Object.getPrototypeOf(Animal.prototype) === Object.prototype
Output: true, true, true
Explanation: `class B extends A` wires `B.prototype.__proto__ = A.prototype`, terminating at `Object.prototype` whose own proto is `null`.class Animal {}
class Dog extends Animal {}
const d = new Dog();
// describe the chain