//组合继承(伪经典继承)
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 发布
本文通过一个具体示例展示了如何使用组合继承(也称为伪经典继承)在JavaScript中实现对象继承。这种方式结合了构造函数和原型链的优点,使得子类型能够继承父类型的属性和方法。

536

被折叠的 条评论
为什么被折叠?



