Reputation: 73
Have some problem with inheritance. How to implement type inheritance from Some Pencil to Another Pencil? Need: pen3.type // common
class Pencil {
constructor(color) {
this.color = color;
}
intro() {
console.log(`this is ${this.color} pencil`);
}
};
class SomePencil extends Pencil {
constructor(color, type) {
super(color);
this.type = type;
}
};
class AnotherPencil extends SomePencil {
constructor(color,type) {
super(color, type);
}
};
let pen1 = new Pencil();
let pen2 = new SomePencil("red", "common");
let pen3 = new AnotherPencil("green");
console.log("type" in pen3); // true
Upvotes: 2
Views: 63
Reputation: 7273
Inheritance will only inherit properties and not values unless they are set in the class definition itself. For example
class SomePencil extends Pencil {
constructor(color, type) {
super(color);
this.type = type || 'common'; // Setting a default value if type is not passed
}
};
new way to set defaults
class SomePencil extends Pencil {
constructor(color, type = 'common') {
super(color);
this.type = type;
}
};
Refer jsfiddle
Upvotes: 1