1.原型链继承:
利用原型让一个引用类型继承另一个引用类型的属性和方法。
优点:子类不仅仅可以访问父类原型上的属性和方法,也可以访问从父类构造函数中复制的属性和方法。
缺点:(1)包含引用类型值的原型属性会被所有的实例共享, 通过原型来实现继承的时候, 原型实际变成了另外一个函数的实例。
(2)在创建子类型的实例时,不能传递参数。
function Person(){
}
Person.prototype.cry=function(){
console.log("Crying");
}
function Child(){
}
Child.prototype=new Person();
var child=new Child();
//检测对象类型
console.log(child instanceof Child); //true
console.log(child instanceof Person); //true
console.log(child instanceof Object); //true
2.构造函数继承
在子类的构造函数中,通过 apply()
或 call()
的形式,调用父类构造函数以实现继承。
apply:最多只能有两个参数——新this对象和一个数组argArray。
call:有多个参数,第一个参数与apply一样,后面是参数列表。
优点:避免了引用类型的属性被所有实例共享,而且可以在子类中向父类传参。
缺点:(1)占用内存大。(2)构造函数继承不能继承父类的原型方法和属性。
function People() {
this.name = arguments[0];
this.sex = arguments[1];
this.eat = function () {
return this.name + "正在吃饭!";
}
}
function Student() {
this.score = arguments[0];
this.writezuoye = function () {
return this.name + "写作业";
}
}
//构造继承不能继承父类的原型方法和属性
Student.prototype.work = function () {
return this.name + "跑步";
}
function smallchildren(name, sex, score) {
People.apply(this, [name, sex]);
Student.call(this, score);
}
var small = new smallchildren("张三", "男", 123);
console.log(small instanceof People);//false
console.log(small instanceof smallchildren);//true
console.log(small);
console.log(small.eat());
console.log(small.writezuoye());
3.组合继承
指的是将原型链和借用构造函数的技术组合到一块,使用原型链实现对原型属性和方法的继承,而通过借用构造函数来实现对实例属性的继承。这样,既通过在原型上定义方法实现了函数复用,又能够保证每个实例都有它自己的属性。
function Mutou() {
this.name = arguments[0];
this.make = function () {
return "制作" + this.name;
}
}
function Bandeng(name) {
Mutou.call(this, name);
}
Bandeng.prototype = new Mutou();
var ban = new Bandeng("板凳");
console.log(ban);
console.log(ban.make());
console.log(ban instanceof Bandeng);
console.log(ban instanceof Mutou);
console.log(window);
4.实例继承
特点:不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果。
缺点:实例是父类的实例,不是子类的实例;不支持多继承。
function Animal(name){
this.run=function(){
return this.name + "在跑~";
}
}
Animal.prototype.walk=function(){
return this.name + "在走~";
};
function Koala(){
this.hao="nice";
var instances=new Animal();
instances.name="张三";
return instances; // 返回这个父类
}
Koala.prototype.sleep=function(){
return this.name+"睡觉"
};
var koala=new Koala(); // 实例是父类的实例,不是子类的实例
console.log(koala.name);//张三
console.log(koala.run());//张三在跑~
console.log(koala.walk());//张三在走~