JavaScript 中常用的继承方式 梳理理解

78 阅读2分钟

构造函数的继承

function fn1 (name){

    this.name = name
    this.abc = name
}
    fn1.prototype.set = ()=>{
        console.log(123)
    }
        
    function fn2 (age){
        this.age = age
        // 构造函数继承修改this 指向
        fn1.call( this, 18)

    }

    const s = new fn2(22)  

    console.log(s.name,s.abc) // 通过实例化对象 在自身调用 继承的 fn1中的属性
        /**
         * 
         * 方式 :通过直接的调用 修改其的this 指向  -- 
         * 优点:继承函数的子类具有父类的实际的方法和属性
         * 
         * 缺点:但是没法继承 父类的原型中的内容 
        */

原型继承

        function fn1 (name){
            this.name = name
        }
        
        const  f = new fn1()

        function fn2 (age){
            this.age = age
        }
        // 实例化后原型继承
        fn2.prototype = new fn1('张三')
        const s = new fn2()
        
        console.log(s.name)
        /**
           方式:将父类函数中的内容实例化 赋值给子类的原型中
         * 缺点:1 自身构造函数的原型内容被覆盖 污染
         *       2 自己并不具有继承的属性和方法 只是能够在调用时继承父类的属性方法的使用   
        */

组合继承

             function fn1 (name){
                this.name = name
                this.abc = name
            }
            fn1.prototype.set = ()=>{
                console.log(123)
            }



            function fn2 (age){
                this.age = age
                // 构造函数继承修改this 指向
                fn1.call( this, 18)


            }
            // 实例化后原型继承
            fn2.prototype = new fn1()

            const s = new fn2(22)

            console.log(s)
            console.log(fn2.prototype)
            /**
             * 优点:1 子类自身能够继承到父类的属性和方法
             *       2 并且能够继承到父类构造函数原型中的内容
             * 
             * 缺点:
             *      使其子类多了一套多余的父类的方法和属性
            */

拷贝继承

            function fn1 (name){
                this.name = name
                this.abc = name
            }
            fn1.prototype.set = ()=>{
                console.log(123)
            }

            function fn2 (age){

                this.age = age
                // 实例化 fn1
                const object = new fn1(18)
                // 遍历拿到需要继承的实例化对象中的所有方法和属性 包括原型中的
                for (const key in object) {
                    // 把拿到的所有内容赋值给子类中的原型 实现继承
                    fn2.prototype[key] = object[key]
                } 
            }

            const s = new fn2(22)
            console.log(s.name,s.abc) // 通过实例化对象 在自身调用 继承的 fn1中的属性

ES6 的继承方法

1
    class op1{
        constructor(age){
            this.age = age
            
        }

        set(){
            const fn1 = function (){
                console.log(123)
            }
            return fn1
        }
     }

    

实现类2(空) 拷贝类1

     class op2 extends op1{
        constructor(sex){
            super(18)
            this.sex = sex
        }
     }
     //实例化
    const s = new op2('男')
    
     console.log(s.age) //拥有类一的属性 
    //  let newFn = s.set()// 通过实例化对象 调用继承类1 中的方法
    //  newFn()