es5的类的继承
存在问题 Person1 执行了两次,造成了多构造一次的性能开销
组合继承
function Person(name, age) {
this.name = name
this.age = age
this.say = function () { //this不能少
console.log(this.name, this.age)
}
}
Person.prototype.eat = function () {
console.log("hello")
}
function Person1(name, age, sex) {
//this指向其实例化对象
Person.call(this, name, age) //参数一个都不能少
this.name = name
this.age = age
this.sex = sex
}
Person1.prototype = new Person(); // Person1.prototype原型对象被重置 Parent.prototype 也可以实现
Person1.prototype.constructor = Person1 || Person.prototype
; //再次指回原来的实例方法
Person1.prototype.run = function () {
console.log(this.name, this.age, this.sex)
}
var p1 = new Person("李白", 15)
var p2 = new Person1("李白", 15, "男")
p1.eat() //hello
p2.run() //李白 15 男
p2.eat() //hello
p2.say() //李白 15
寄生组合式继承
function Parent(name, age) {
this.name = name,
this.age = age
}
Parent.prototype.Say = function () {
console.log(this.name);
}
function Children(name, age,sex) {
Parent.call(this, name, age) // 1
this.sex=sex
}
// 2
Children.prototype = Object.create(Parent.prototype); // 这就是不同
// 3
Children.prototype.constructor = Children;
let p1 = new Children("小王", 18,"man")
console.log(p1); // Children { name: '小王', age: 18, sex: 'man' }
p1.Say()
ES6中的类的继承
实际也是使用寄生组合式继承来实现的
子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
class Father {
constructor(x, y) {
this.x = x
this.y = y
}
sum() {
console.log(this.x + this.y)
}
}
class son extends Father { //继承父类
constructor(x, y,z) { //不能用this
super(x, y) //调用父类的构造函数,通过super.sum()也可以直接调用父类的方法
this.z=z
}
}
var pop = new son(1, 2)
pop.sum()