js中的继承方法:
1、构造函数方法继承(用call()方法)
function Father(a,b) {
this.a = a
this.b = b
}
function Children () {
Father.call(this, a, b) // 将父构造函数的this指向子构造函数的实例,从而实现继承
}
缺点:1、无法继承父构造函数的原型对象的方法,2、每次创建子构造函数实例都会添加父构造函数的方法,导致占用内存大
2、原型链继承
function Father(a,b) {
this.a = a
this.b = b
}
function Children (c) {
this.c = c
}
Children.prototype = new Father() // 将子构造函数的原型对象指向父构造函数的实例
Children.prototype.constructor = Children // 作用是让constructor 重新指向子构造函数
这种方式会重写子构造函数的原型对象,(Children.prototype.constructor === Father)
缺点:
- 可以直接修改父构造函数属性值
- 无法向父构造函数传递参数
注意:给子构造函数的原型对象上添加方法时必须在Children.prototype = new Father()之后,否则无法调用
3、组合继承
function Father(a,b) {
this.a = a
this.b = b
}
function Children () {
Father.call(this, a, b) // 继承父构造函数的属性方法同时可以传参
}
Children.prototype = new Father() // 继承父构造函数的属性方法以及原型对象的属性和方法
Children.prototype.constructor = Children // 作用是让constructor 重新指向子构造函数
缺点:父构造函数的属性和方法会被绑定和执行两次
4、寄生式组合继承(优化组合式存在的缺点)
function Father(a,b) {
this.a = a
this.b = b
}
function Children () {
Father.call(this, a, b) // 继承父构造函数的属性方法同时可以传参
}
function Super () {} // 添加一个媒介Super构造函数
Super.prototype = Father.prototype // Super构造函数的原型对象指向父构造函数的原型对象,实现继承父构造函数的原型对象的属性和方法,同时不用二次绑定父构造函数的属性和方法
Children.prototype = new Super () // 将子构造函数的原型对象指向Super构造函数实例
Children.prototype.constructor = Children
5、拷贝继承
function Person(age) {
This.age = age
}
function Student(name, age) {
var person = new Person(age);
for (var key in person) {
this.name = name;
if. (person . hasOwnProperty(key)) { // 不是Person原型对象的属性
this[key] = person[key];
}else{
Student . prototype[key] = person[key]; // 是Person原型对象的属性,添加到Student构造函数的原型对象上
}
}
}