1.原型链继承( 将父类的实例作为子类的原型)
function animal(){
this.name=null;
this.sleep=function(){
return this.name+"睡觉";
}
}
function dog(){
this.type="犬科";
}
animal.prototype.eat=function(){
return "吃东西";
}
var Animal=new animal();
dog.prototype=Animal;
dog.prototype.color="red";//要为子类追加属性或者方法要放在原型链继承对象之后
var Dog=new dog();
console.log(Dog instanceof dog);//对象的实例是子类的实例
console.log(Dog instanceof animal);对象的实例是父类的实例
特点:
非常纯粹的继承关系,
父类新增原型方法/原型属性,子类都能访问到
简单,易于实现
缺点:
单继承
不能放到构造器中无法实现多继承
创建子类实例时,无法向父类构造函数传参
2.构造函数继承(通过apply call改变)
function people(){ //定义一个people父类
this.skycolor=arguments[0];
this.name=arguments[1];
this.sleep=function(){
return this.name+"睡觉";
}
}
function child() {//定义另一个child父类
this.work=function(){
return "学习";
}
}t
child.prototype.play=function(){//child父类通过原型链追加play方法
return "玩";
}//不能继承父类原型链属性及方法;
function student(color,name){
//people.apply(this,[color,name]);
people.call(this,color,name);
child.call(this);//可以继承多个对象
Student=new student("yellow","毛毛");
console.log(Student instanceof student);//对象的实例是子类的实例
console.log(Student);
var children=new child();
console.log(children.play());
call和apply区别
call 参数传递是散列分布
Fun_A.call(Fun_B , arg1 , arg1 …)
按理说一个函数调用时指向是当前函数执行环境中Fun_A,使用call之后,现在的this指向了Fun_B执行环境中 ,
apply 参数传递是以数组的方式
Fun_A.apply(Fun_B , [arg1 , arg1 …])
同样的将this指向了Fun_B的执行环境中。
3.实例继承(不支持多继承)
function f1() { //定义一个f1类
this.name = null;
this.sleep = function () {
return "睡觉";
}
}
function f2() {
var f = new f1(); //new对象返回对象
return f;
}
var fchild = new f2(); //对象的实例化
console.log(fchild);
console.log(fchild instanceof f2);//false 对象的实例不是子类的实例
console.log(fchild instanceof f1);//true 对象的实例是父类的实例;
var ff = f2();
4.组合继承
function Mutou() { //定义一个mutou这个父类
this.name = arguments[0];
this.make = function () {
return "制作" + this.name;
}
}
function Bandeng(name) { //定义bandeng这个类并且通过构造函数继承mutou这个类
Mutou.call(this, name);
}
Bandeng.prototype = new Mutou();//bandeng这个类通过原型链追加继承mutou 这个类
var ban = new Bandeng("板凳"); //bandeng对象的实例化;
console.log(ban);
console.log(ban.make());
console.log(ban instanceof Bandeng); //对象的实例是父类的实例;
console.log(ban instanceof Mutou);//对象的实例是子类的实例;
特点:弥补了方式2 的缺陷
缺点:生成了两个实例,消耗内存;