0

To test my understanding of how classes work and how they can be emulated, I've done the following:

function Electronic(category) {
    this.category = category;
    this.state = 0;
}
Electronic.prototype.toString = function() {
    return `The ${this.category} is turned ${this.state? "on" : "off"}.`;
}
function Computer(brand) {
    Electronic.call(this, 'Computer');
    this.brand = brand;
}
Computer.prototype = Electronic.prototype;
Computer.prototype.constructor = Computer;
Computer.prototype.toString = function() {
    // how to get the super.toString() method here?
    return `${Electronic.prototype.toString()} The brand is ${this.brand}.`;

}
c = new Computer('Dell');
console.log('' + c);

However, in trying to override the toString() method (while also retrieving the parent value), I'm running into a recursion error.

It seems the following works if I alias a parent method, but I'm wondering if it's possible to do it without changing one of the method names?

function Electronic(category) {
    this.category = category;
    this.state = 0;
}
Electronic.prototype._toString = function() {
    return `The ${this.category} is turned ${this.state? "on" : "off"}.`;
}
function Computer(brand) {
    Electronic.call(this, 'Computer');
    this.brand = brand;
}
Computer.prototype = Electronic.prototype;
Computer.prototype.constructor = Computer;
Computer.prototype.toString = function() {
    return `${Electronic.prototype._toString.call(this)} The brand is ${this.brand}.`;
}
c = new Computer('Dell');
console.log('' + c);
David542
  • 104,438
  • 178
  • 489
  • 842
  • 2
    After you do `Computer.prototype = Electronic.prototype;`, anything you assign to `Computer.prototype.xxx` also affects `Electronic.prototype.xxx`, since they're the same object. – Barmar Feb 05 '22 at 22:34
  • This is not how you do prototype inheritance in JavaScript. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain for the correct way. – Barmar Feb 05 '22 at 22:36
  • @Barmar perfect, thanks for the suggestion. Doing the proper `[[prototype]]` assignment fixes it: `Computer.prototype = Object.create(Electronic.prototype);` – David542 Feb 05 '22 at 23:01

0 Answers0