such as the title, I recently found a puzzling problem when I was flipping through the Red Treasure Book.
mentions combinatorial inheritance in the chapter of 6.3inheritance, which is explained as follows:
js:
so here comes the problem. We all know what the prototype chain and constructor are, so what about borrowing the constructor?
then give an example of borrowing a constructor:
function SuperType(){
this.colors = ["red", "blue", "green"];
}
function SubType(){
// SuperType
SuperType.call(this);
}
var instance1 = new SubType(); instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
var instance2 = new SubType();
alert(instance2.colors); //"red,blue,green"
what puzzles me is why the constructor is borrowed, as in the above code, the superclass is called in the parent class to add subclass private properties to the subclass.
Why can"t this be done using a constructor?
Constructors can be implemented as well, and constructors are simpler than borrowing constructor structures. In the example where
is changed to a constructor, the utility is the same as borrowing the constructor:
function SubType() {
this.colors = ["red", "blue", "green"];
}
var instance1 = new SubType();
instance1.colors.push("black");
alert(instance1.colors); //"red,blue,green,black"
var instance2 = new SubType();
alert(instance2.colors); //"red,blue,green"
so let me emphasize my question again: why use borrowing constructors in combinatorial inheritance instead of using constructors directly? In my opinion, constructors are simpler and functionally consistent than borrowing constructors.