原型继承
子类继承父类的属性和方法
继承方式:Child.prototype = new Person();
添加原型属性和方法:Person.prototype.color = "黄";
| 优点 | 缺点 |
---|
子类实例 instanceof 父类 | √ | |
继承子类构造属性方法construction | √ | |
继承父类构造属性方法construction | √ | |
继承父类原型属性方法prototype | √ | |
给父类传递参数 | | × |
多继承 | | × |
原型链
var arr = new Array();
console.log(arr);
console.log(arr.__proto__);
console.log(arr.__proto__.__proto__);
Child.prototype = new Person();
var child = new Child();
console.log(child.__proto__);
console.log(child.__proto__.__proto__);
console.log(child.__proto__.__proto__.__proto__);
console.log(child.__proto__.__proto__.__proto__.__proto__);
构造继承
function Cat(n,se, ag,typ) {
this.name = n;
this.eat = function () {
return "吃东西"
}
Animail.apply(this,[se, ag]);
Type.call(this,typ);
}
| 优点 | 缺点 |
---|
给父类传递参数 | √ | |
多继承 | √ | |
继承子类构造属性方法construction | √ | |
继承父类构造属性方法construction | √ | |
子类实例 instanceof 父类 | | × |
继承父类原型属性方法prototype | | × |
组合继承:原型继承+构造继承
function Child(n, a, s) {
this.age = a;
this.sex = s;
Person.call(this, n);
}
Child.prototype = new Array();
| 优点 | 缺点 |
---|
给父类传递参数 | √ | |
多继承 | √ | |
继承子类构造属性方法construction | √ | |
继承父类构造属性方法construction | √ | |
子类实例 instanceof 父类 | √ | |
继承父类原型属性方法prototype | √ | |
寄生组合继承:避免两次调用父类构造函数
* 寄生组合继承:处理组合继承的缺点 ,避免两次调用父类的构造函数
* 原理是把父类的原型给予一个空对象的原型
(function () {
var fn = function () {};
fn.prototype = Person.prototype;
Child.prototype = new fn();
})();
实例继承
继承方式:子类里面 实例化父类,并返回父类实例
function Child(n, s) {
var per = new Person(n, s);
return per;
}
| 优点 | 缺点 |
---|
多继承 | | × |
继承子类构造属性方法construction | | × |
子类实例 instanceof 子类 | | × |
子类实例 instanceof 父类 | √ | |
继承父类构造属性方法construction | √ | |
继承父类原型属性方法prototype | √ | |
给父类传递参数 | √ | |
拷贝继承(占内存,不建议使用)
继承方式:将父类里面的属性方法拷贝给子类
function Cat(n, a) {
this.age = a;
var animal = new Animal(n);
for (var p in animal) {
Cat.prototype[p] = animal[p];
}
}
| 优点 | 缺点 |
---|
继承子类构造属性方法construction | | × |
子类实例 instanceof 父类 | | × |
继承父类构造属性方法construction | √ | |
给父类传递参数 | √ | |
多继承 | √ | |