关于JS的继承,小白的看法。

137 阅读2分钟

1.原型链继承

function Father(){
        this.name="我是父";
        this.sell=function(){
            console.log("我的名字是"+this.name);
        }
    }
    function Son(age){
        this.age=age;
    }
    Son.prototype=new Father();
    let p1=new Son(18);
    console.log(p1.name);  //我是父

缺点:

1.在创建子实例的时候无法向父构造函数传参;

2.对于应用类型的属性被继承,实例对其修改会同时修改调其它实例的该属性,该属性被所有的实例所共享;

2.构造函数继承

function Father(name){
        this.name=name;
        this.sell=function(){
            console.log("我的名字是"+this.name);
        }
    }
    function Son(name,age){
        this.age=age;
        //利用call方法来给自己添加父类的属性
        Father.call(this,name);
    }
    let p1=new Son("小明",18);
    console.log(p1);  //小明

优点:

1.可以在创建子实例时向父构造函数传参;

2.因为是用.call方法来实现,所以可以同时继承多个构造函数;

3.当属性为应用类型时,也不户出现属性共享的情况;

缺点:

1.没有继承父构造函数原型上的属性。

3.组合式继承

原型链式继承与构造函数继承结合:

function Father(name){
        this.name=name;
        this.sell=function(){
            console.log("我的名字是"+this.name);
        }
    }
    Father.prototype.message='abc';
    function Son(name,age){
        this.age=age;
        Father.call(this,name);
    }
    Son.prototype=new Father();
    let p1=new Son("小明",18);
    console.log(p1.message);  //abc

优点:

1.可以继承父构造函数上的属性;

缺点:

1.调用了两个父构造函数;

4.原型式继承

function Father(name) {
        this.name = name;
        this.sell = function () {
            console.log("我的名字是" + this.name);
        }
    }
    function createNewObj(obj) {
        function F() { };
        F.prototype = obj;
        return new F();
    }
    let p1 = createNewObj(new Father('小明'));
    p1.age=20;
    console.log(p1.age);//20

特点:利用一个工厂函数来返回一个新对象,有点类似Object.create()的过程

缺点:实例的新属性都要后面一一添加

5.寄生式继承

function Father(name) {
        this.name = name;
        this.obj={}
        this.sell = function () {
            console.log("我的名字是" + this.name);
        }
    }
    function createNewObj(obj) {
        function F() { };
        F.prototype = obj;
        return new F();
    }
    function createNewObjAdd(obj){
        let one=createNewObj(obj);
        one.age=20;
        return one;
    }
    let p1=createNewObjAdd(new Father('小明'));
    console.log(p1.age)

特点:其实就是在原型式继承的又加了一层函数封装,用于添加新的属性和方法,但是根本性的问题还是没有改变。

6.寄生组合式继承

function Father(name) {
        this.name = name;
        this.obj={}
        this.sell = function () {
            console.log("我的名字是" + this.name);
        }
    }

    function Son(name,age){
        this.age=age;
        Father.call(this,name);
    }
    function createNewObj(obj) {
        function F() { };
        F.prototype = obj;
        return new F();
    }
    function content(son,father){
        let one=createNewObj(father.prototype);
        one.constructor=son;
        son.prototype=one;
    }
    content(Son,Father);
    let p1=new Son("小明",20);
    console.log(p1);

特点:可以利用构造函数给父类传参,并且父类构造函数只执行了一次,我个人认为这种继承方式是最好的;