美文网首页
JS 的继承

JS 的继承

作者: 呆桃冲鸭冲鸭 | 来源:发表于2021-03-02 10:11 被阅读0次

    JS 的继承实现方式:
    第一种:原型链继承
    缺点:两个实例使用的是同一个原型对象,它们的内存空间是共享的,当一个发生变化的时候,另外一个也随之进行了变化,

    第二种:构造函数继承(借助 call)

        function Parent1(){
            this.name = 'parent1';
        };
        Parent1.prototype.getName = function () {
            return this.name;
        };
        function Child1(){
            Parent1.call(this);
            this.type = 'child1'
        };
        let test = new  Parent1();
        console.log(test); // {name: "parent1"}
        let child = new Child1();
        console.log(child);  //{name: "parent1", type: "child1"}
        console.log(child.getName());  // 会报错
    

    优点:它使父类的引用属性不会被共享
    缺点:只能继承父类的实例属性和方法,不能继承原型属性或者方法。

    第三种:组合继承(原型链继承和构造函数继承组合)

        function Parent3 () {
            this.name = 'parent3';
            this.play = [1, 2, 3];
        };
        Parent3.prototype.getName = function () {
            return this.name;
        };
        function Child3() {
            // 第二次调用 Parent3()
            Parent3.call(this);
            this.type = 'child3';
        };
        // 第一次调用 Parent3()
        Child3.prototype = new Parent3();
        // 手动挂上构造器,指向自己的构造函数
        Child3.prototype.constructor = Child3;
        var s3 = new Child3();
        var s4 = new Child3();
        s3.play.push(4);
        console.log(s3.play, s4.play);  // 不互相影响
        console.log(s3.getName()); // 正常输出'parent3'
        console.log(s4.getName()); // 正常输出'parent3'
    

    第四种:原型式继承( Object.create 方法:这个方法接收两个参数:一是用作新对象原型的对象、二是为新对象定义额外属性的对象(可选参数) )

    第五种:寄生式继承
    使用原型式继承可以获得一份目标对象的浅拷贝,然后利用这个浅拷贝的能力再进行增强,添加一些方法,这样的继承方式就叫作寄生式继承。

    第六种:寄生组合式继承


    image.png

    相关文章

      网友评论

          本文标题:JS 的继承

          本文链接:https://www.haomeiwen.com/subject/jljzfltx.html