构造函数和继承

81 阅读1分钟

构造函数

        function Car(color,price){
            this.color = color
            this.price = price
            this.run = function(){
                document.write(`
                <p>颜色:${this.color}</p>
                <p>价格:${this.price}</p>
                `)
            }
        }
        let bmw = new Car('red',100);
        bmw.run();

    </script>

去除空格

        String.prototype.ClearLSpace = function(){
            return this.replace(/\s+$/,'')
        }
        String.prototype.ClearFSpace = function(){
            return this.replace(/^\s+/,'')
        }
        String.prototype.ClearAllFSpace = function(){
            return this.replaceAll(/\s+/g,'')
        }
        let nstr = 'abc    '.ClearLSpace();
        console.log(nstr)
        let nstr2 = '   ab  c    '.ClearFSpace().ClearLSpace();
        console.log(nstr2)
        let nstr3 = '   ab  c  '.ClearAllFSpace();
        console.log(nstr3)
    </script>

继承

        // function Car(){
        //     this.color = 'red'
        //     this.price = 100
        // }
        // function Bmw(type){
        //     this.type = type
        // }
        // Bmw.prototype = new Car();
        // Bmw.prototype.constructor = Bmw;
        



        // function Car(){}
        // function Bmw(){}
        // Car.prototype.color = 'red'
        // Car.prototype.price = 100
        // Bmw.prototype = Car.prototype;




        function Car(){}
        Car.prototype.color = 'red'
        Car.prototype.price = 100
        function f(){}
        f.prototype = Car.prototype
        function Bmw(){}
        Bmw.prototype = new f;
        Bmw.prototype.constructor = Bmw;
        let str = new Bmw();
        document.write(str.color,str.price)

    </script>