js原型、继承

93 阅读1分钟

原型

每一个函数都有一个prototype(原型)属性, 是一个指针,指向一个对象, 这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法, 构造函数原型 prototype
构造函数通过原型分配的函数时所有对象所共享的,它的作用就是共享方法

示例:

    <script>
        function Car(name,color,price){
        this.name = name;
        this.color = color;
        this.price = price;
    }
    Car.prototype.run = function(){
        document.write(document.write(
                `
                车名:${this.name}<br>
                颜色:${this.color}<br>
                价格:${this.price}<br>
                会跑
                `
            ))
    }
    let c1 = new Car('宝马','绿色',30+'w')
    c1.run();
</script>

原型的方法清除空格

<script>
  String.prototype.clearAllSpace = function(){
    return  this.replace(/\s/g,'')//去除全部
  }
  String.prototype.clearQSpace = function(){
    return  this.replace(/^\s+/g,'')//去除前空格
  }
  String.prototype.clearHSpace = function(){
    return  this.replace(/\s+$/g,'')//去除后空格
  }
  String.prototype.clearQHSpace = function(){
    return  this.replace(/^\s+|\s+$/g,'')//去除前后空格
  }
let newStr = '  ab  c       '.clearAllSpace();
console.log(newStr);
let a = '   abd'.clearQSpace();
console.log(a);
let b = '   avs   '.clearQHSpace();
console.log(b);
let str = new String();
console.log(str);
</script> 

js面向对象继承

 <script>
    function Person(name,age){
        this.name= name;
        this.age  =aeg;
    }
    let p1 = new Person('zhansgan',30)
</script> -->

构造函数可以理解为一个类

<!-- constructor将这个属性指回原来的构造函数 -->
 <script>
     function Person(name,age){
        this.name= name;
        this.age = age;
    }
    function Student(name,age){
        this.name = name;
        this.age = age;
    }
    Student.prototype = new Person();
    Student.prototype.constructor = Student;
    let stu = new Student();
    console.log(stu);
</script>

练习

写一个类Car color price 属性

  • 类Bmw继承Car的所有属性并实例化Bmw这个类写个方法可以把 color和 price 打印到页面上
<script>
    function Car(color,price){
        this.color = '红色';
        this.price = '3000w';
    }
    function Bmw(){
    }
    Bmw.prototype = new Car();
    Bmw.prototype.constructor = Bmw;
    let b1 = new Bmw();
    document.write(
        `
        颜色:${b1.color}
        价格:${b1.price}
        `
    )
</script> 

为了使用起来更加方变,所有用空对象封装的方法 实现继承

<script>
    function Car(color, price) { }
    Car.prototype.color = '红色'
    Car.prototype.price = '30w'

    function Bmw(){

            }
    function extend(Child, Parent) {   //传子元素和父元素
        var f = function () { };
        f.prototype = Parent.prototype;
        Child.prototype = new f();
        Child.prototype.constructor = Child;
        Child.uber = Parent.prototype;
    }
    
    extend(Bmw,Car)
    let c1 = new Bmw();
    console.log(c1);
</script>