【红宝书p244组合继承】
1,父类属性放构造函数里,方法放原型里,让子类继承后,查看子类结构
function SuperType(name){
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function() {
//以后子类实例可直接共用,不用重写的属性或方法写入父类的原型里面
console.log(this.name);
};
function SubType(name, age){
// 继承属性
SuperType.call(this, name);
this.age = age;
}
// 继承方法
SubType.prototype = new SuperType();
console.dir(SubType);
2,子类组合继承父类且实例化后,子类的结构
<script>
function SuperType(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
SuperType.prototype.sayName = function () {
console.log(this.name);
};
function SubType(name, age) {
// 继承属性
SuperType.call(this, name);
this.age = age;
}
// 继承方法
SubType.prototype = new SuperType();
//实例化对象
let sub = new SubType('ike', 18);
console.dir(sub);
</script>