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);