构造函数和继承

124 阅读1分钟

构造函数 首字母大写 不需要return

 <script>
        function Fa(car, color, price) {
            this.car = car;
            this.color = color;
            this.price = price;
            this.run = function () {
                document.write(
                    `
                ${this.car}
                ${this.color}
                ${this.price}
                `
                )
            }
        }
        let p1 = new Fa('奥迪','粉色','不要998,只要9快8');
        p1.run();

    </script>

继承:

  • 原型链继承实列化对象
<script>
        function Car(color,price){
        this.color='粉色';
        this.price=9.9
        }
        function Bmw(){

        }
        Bmw.prototype = new Car;
        Bmw.prototype.constructor = Bmw;
        let b1 = new Bmw;
        document.write(
            `
            ${b1.color}
            ${b1.price}
            `
        )
        console.log(b1);
    </script>
  • 原型链继承直接继承原型
<script>
        function Car(color,price){
        
        }
        Car.prototype.color='粉色'
        Car.prototype.price='不要998,不要888,只要9快8!!!!'
        Bmw.prototype=Car.prototype;
        function Bmw(){
            this.inpro=function(){
                document.write(
            `
            ${b1.color}
            ${b1.price}
            `
        )
            }
        }
        let b1 = new Bmw;
        b1.inpro()
        console.log(b1);
    </script>
</body>
  • 利用空对象作为中介
  • 空对象,几乎不占内存
  • 修改Student的prototype对象,不会影响到Person的prototype对象
 function fz(child,parent){
            function f(){};
        f.prototype = parent.prototype;
        child.prototype = new f();
        child.prototype.constructor = child;
        }
        /* 父类 */
        function House(price){}
        House.prototype.price='100w';
        /* 子类 */
        function Tangc(){
            this.name = '汤臣一品'
            this.roo = function(){
                document.write(
                    `
                    '钱:'${this.price}<br>
                    '房子'${this.name}
                    `
                )
            }
        };
        fz(Tangc,House);
        let p1 = new Tangc();
        console.log(p1.price);
        p1.roo()