<JS:类的寄生组合继承>
<JS:类的寄生组合继承>2024年6月3日
本帖最后由 tzbm123456 于 2024-6-3 10:48 编辑
// 父构造函数
function Parent(name) {
this.name = name;
}
// 父构造函数的原型方法
Parent.prototype.sayName = function() {
console.log('My name is ' + this.name);
};
// 子构造函数
function Child(name, age) {
Parent.call(this, name); // 调用父构造函数,继承属性
this.age = age;
}
// 创建一个Parent的原型的实例,将其作为Child的原型
Child.prototype = Object.create(Parent.prototype);
// 修正Child.prototype的构造器指向
Child.prototype.constructor = Child;
// 重写sayName方法,新增('My age is ' + this.age)功能
Child.prototype.sayName = function() {
Parent.prototype.sayName.call(this);
console.log('My age is ' + this.age);
};
cc=new Child('Tzbm',53);
// cc.sayName()
// My name is Tzbm
// My age is 53
页:
[1]