「寄生组合式继承」subType子 superType父
function inheritPrototype(subType, superType) {
创建对象,创建父类原型的一个副本
var prototype = Object.create(superType.prototype);
console.log(prototype, 55)
增强对象,弥补因重写原型而失去的默认的constructor 属性
prototype.constructor = subType;
console.log(prototype, 34)
指定对象,将新创建的对象赋值给子类的原型
subType.prototype = prototype;
console.log(prototype, 44)
}
function Father(name) {
this.name = name;
this.colors = ["red", "blue", "green"];
}
Father.prototype.sayName = function () {
alert(this.name);
};
借用构造函数传递增强子类实例属性(支持传参和避免篡改)
function Son(name, age) {
Father.call(this, name);
this.age = age;
}
将父类原型指向子类
inheritPrototype(Son, Father);
新增子类原型属性
Son.prototype.sayAge = function () {
alert(this.age);
}
var demo1 = new Son("TianTian", 21);
var demo2 = new Son("TianTianUp", 20);
demo1.colors.push("2");
demo2.colors.push("3");
demo2.sayName()
console.log(demo1)
Class实现继承👇
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width;
}
}
const rectangle = new Rectangle(40, 20);
console.log(rectangle.area);
class Square extends Rectangle {
constructor(len) {
super(len, len);
this.name = 'SquareIng';
}
get area() {
return this.height * this.width;
}
}
const square = new Square(20);
console.log(square.area);