Senior
Explain the inheritance problem in code where a class extends Object, and suggest a solution.
sobes.tech AI
Answer from AI
In JavaScript, all objects inherit from Object.prototype by default. If you explicitly write class MyClass extends Object, it is redundant and can lead to confusion, especially if you try to override methods of the base object later on.
The problem is that inheriting from Object does not add any functionality and can complicate the prototype chain if you do not understand that Object is the root of all objects. Sometimes, this leads to unexpected errors, for example, if methods like toString or hasOwnProperty are overridden.
Solution:
- Do not explicitly specify
extends Objectunless there is a specific reason. - If you need to create an object without a prototype, use
Object.create(null). - For classes, inherit from more specific classes rather than directly from
Object.
Example:
// No need to explicitly write extends Object
class MyClass {
constructor(name) {
this.name = name;
}
}
const obj = new MyClass('test');
console.log(obj.toString()); // works because it inherits from Object.prototype