JavaScript 继承(原型链 构造 实例 组合)

实例化对象

function Animal(){
     this.name=null;
     this.sleep=function(){
     return "睡觉";
     };
     this.eat=function(){
     return "吃";  
     }
}
var animal=new Animal();
console.log(animal);

//原型链继承  _proto_
function Dog(){
   this.type="犬"}
Dog.prototype=new Animal();
Dog.prototype.color="red"; //想为子类添加属性要放在原型链继承之后进行 否则会被覆盖
var dog=new Dog();
console.log(dog);   //dog将继承Animal的属性
console.log(typeof dog);   //object
console.log(dog instanceof Dog);  //检测dog的实例对象是不是Dog 是的话返回true
console.log(dog instanceof Animal);  //true

原型链继承 单继承 实例是子类的实例也是父类的实例。
在数组上封装一个方法去调用执行 进行数组的排序

Array.prototype.mySort=function(){
}
var a=[1,3,2,9,8];
a.mySort();

构造继承 call apply 对象指针的替换。 子类的实例是自身 而不是父类。_proto_为object。 call有多个参数,apply有两个参数。 构造继承不能继承父类的原型方法和属性,不能追加。只继承父类现有的方法。Student.prototype.work=function(){return this.name+"跑步"}无效。

function People(){
    this.sex=null;
    this.eat=function(){
         return "吃";
    }
}
function children(){
        People.call(this);   // People.apply(this); 
    }
    var child=new children();
    console.log(child);
    console.log(child instanceof children);  //true
    console.log(child instanceof People);  //false

在这里插入图片描述
构造继承 多继承

//构造继承传参
function people(){
    this.name=arguments[0];
    this.sex=arguments[1];
    this.eat=function(){
        return this.name+"正在吃饭";
    }
}
function Student(){
    this.score=arguments[0];
    this.wirtezuoye=function(){
        return this.name+"写作业";
    }
}
function children(name,sex,score){
     people.call(this,name,sex);
     //people.apply(this,[name,sex]);   apply方法
     Student.call(this,score);
}
var child=new children("花生","男",99);
console.log(child);
console.log(child.eat());  //花生在吃饭
console.log(child.writezuoye());   //花生在写作业

在这里插入图片描述
在这里插入图片描述
实例继承
new对象返回对象。子类的实例不是自身是父类,不能多继承。

function f1(){
    this.name=null;
    this.sleep=function(){
        return "睡觉";
    }
}
function f2(){
    var f=new f1();
    return f;
}
var fchild=new f2();
console.log(fchild);
console.log(fchild instanceof f2);   //false 实例不是自身
console.log(fchild instanceof f1);   //true 实例是父类

在这里插入图片描述
组合继承
弥补原型链继承和构造继承的缺点。既是子类的实例又是父类的实例。

function mutou(){
    this.name=arguments[0];
    this.mack=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.mack());
console.log(ban instanceof bandeng);   //true
console.log(ban instanceof mutou);     //false 添加bandeng.prototype=new mutou();之后变为true 

在这里插入图片描述

发布了75 篇原创文章 · 获赞 0 · 访问量 3391

猜你喜欢

转载自blog.csdn.net/E_ISOLATE/article/details/100881960