继承

65 阅读1分钟

call和apply

        function Car(gang,bsx){
            this.lunzi = 4
            this.gang = gang
            this.bsx = bsx
        }
        function Vechile(name,price,gang,bsx){
            this.name = name;
            this.price = price;
            // Car.call(this,gang,bsx);
            Car.apply(this,[gang,bsx]);
            this.print = function(){
                document.write(`${this.name}--${this.price}--${this.gang}缸发动机--${this.bsx}变速箱--有${this.lunzi}个轮子`)
            }
        }
        let c1 = new Vechile('奔驰','100w',4,'at');
        c1.print();
    </script>

组合继承

        function Car(name){
            this.lunzi = 4
            this.name = name
        }
        Car.prototype.run = function(){
            document.write(`${this.name}--有${this.lunzi}个轮子,会跑赛道`)
        }
        function Bc(name){
            this.name = name
            Car.call(this,name)
        }
        Bc.prototype = new Car();
        Bc.prototype.constructor = Bc;
        let c1 = new Bc('奔驰')
        c1.run();

    </script>

构造函数绑定继承

        <script>
        // function Person(){
        //     this.foot = 2
        // }
        // function Student(color,price){
        //     Person.call(this)
        // }
        // console.log( new Student('白色','100w') );

      
      
       function Car(gang,bsx){
           this.lunzi = 4;
           this.gang = gang;
           this.bsx = bsx;
       }
       function Bc(name,price,gang,bsx){
           /* 把子类的this传给父类
           使用call来改变this指向,把父类中的this指向子类 */
        //    Car.call(this,gang,bsx);
           Car.apply(this,[gang,bsx])
           this.name = name;
           this.price = price;
           this.print = function (){
                document.write(`
                    ${this.name}--${this.price}--${this.lunzi}个轮子--${this.gang}--${this.bsx}
                `);
           }
       }
       let bc1 = new Bc('奔驰E300','55W','4缸','9AT变速箱');
       bc1.print();
       console.log(bc1);

    </script>

拷贝继承

        function Car(){}
        Car.prototype.lunzi = 4
        Car.prototype.run = function(){
            document.write((`${this.name}--有${this.lunzi}个轮子,会跑赛道`))
        }
        function Bc(name){
            this.name = name
        }
        function extend(child,parent){
            for(let key in parent.prototype){
                child.prototype[key] = parent.prototype[key];
            }
        }
        extend(Bc,Car);
        let c1 = new Bc('benchi');
        c1.run();
    </script>