//组合继承(伪经典继承)
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();
SubType.prototype.constructor = SubType;
SubType.prototype.sayAge = function(){
console.log(this.age);
};
const instance1 = new SubType("Nicholas",29);
instance1.colors.push('black');
console.log(instance1.colors);//'red,blue,green,black';
instance1.sayName();//'Nicholas';
instance1.sayAge();//29
const instance2 = new SubType('Greg',27);
console.log(instance2.colors);//'red,blue,green'
instance2.sayName();//'Greg'
instance2.sayAge();//27
js经典继承
最新推荐文章于 2022-11-11 19:12:17 发布