构造函数继承方法
2020-05-13 本文已影响0人
开着五菱宏光的小白
1.ES5方法
// 组合继承
function Person(name) {
this.name = name;
}
function Chinese(name) {
Person.call(this, name)
}
function proto(child, parent) {
child.prototype = new parent()
child.prototype.constructor = child
}
proto(Chinese, Person)
注意点
- 需要注意的是子类继承父类时prototype不能直接用父类的prototype赋值,这样会共用父类的prototype地址,使子类可以修改父类prototype对象。
- 指向父类的实例化对象,即子类的实例化对象proto指向父类的prototype对象。
- 此时会出现子类的prototype中的constructor指向混乱的问题,所以需要对子类的constructor属性重新赋值
缺点
- 上面的方法会使父构造函数执行两次 Father.call的调用、new Father, 不是很理想
// 寄生组合式继承
function Person(name) {
this.name = name
}
function Chinese(name) {
Person.call(this,name)
}
function create(prototype) {
function Super() {}
Super.prototype = prototype
return new Super()
}
function proto(child, parent) {
const prototype = create(parent.prototype)
prototype.constructor = child
child.prototype = prototype
}
proto(Chinese, Person)
2.ES6
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) {
super(x,y);
}
}
var son = new Son(1,1);
son.sum();
通过super调用父类的普通函数