原型链方式

64 阅读1分钟

原型链/继承实例化对象的方式

`function Car(){
            this.color = '白色'
            this.price = '100w'
        }
        function Bmw(){}`

        Bmw.prototype = new Car();
        Bmw.prototype.constructor = Bmw;

        let b1 = new Bmw();
        console.log(b1.color);
        console.log(b1.price);
        console.log(b1);
    !!会导致被赋值对象的constructor(构造器丢失)

原型链/直接继承的方式

 function Car(){    }
      Car.prototype.color = '白色'
      Car.prototype.price = '100w'
      function Bmw(){
          this.print = function (){
              document.write(`${this.color}--${this.price}`);
          }
      }

      Bmw.prototype = Car.prototype;
      let b1 = new Bmw();
      b1.print();
      console.log(b1);
 !!造成污染 儿子的prototype改动也会导致父亲改动

利用空对象作为中介

  ````
   function Car(){
        
    }
    Car.prototype.color='白色'
    Car.prototype.price='100w'
    function Fn(){}
    Fn.prototype=Car.prototype
    function Bmw(){
        
    }
   Bmw.prototype=new Fn()
   Bmw.prototype.constructor=Bmw
    let b1 = new Bmw();
    console.log(b1.color);
    console.log(b1);
    ````

拷贝继承

function Person(){}
            Person.prototype.head =1;
            Person.prototype.foot =2;
            Person.prototype.eat = function(){
                document.write('我会吃饭')
            };
            function Student(){}
                for(let key in Person.prototype){
                    Student.prototype[key]=Person.prototype[key]

                }
            let stu1=new Student()
            stu1.eat() 
            封装后
            function Person(){}
            Person.prototype.head =1;
            Person.prototype.foot =2;
            Person.prototype.eat = function(){
                document.write('我会吃饭')
            };
            function Son(){ }
            function fn(a,b){
                for(var i in b.prototype ){
                    a.prototype[i]=b.prototype[i]
                }
            }
            fn(Son,Person)
           let aaa=new Son()
           console.log(aaa.head)

组合继承:

含义: 也叫伪经典继承, 原型链和构造函数组合在一块, 原型链实现对原型属性和方法的继承, 借用构造函数实现对实例属性的继承
    function Person() {
        // 实例属性
        this.foot = 2;
        this.head = 1;
    }
    // 原型属性和方法
    Person.prototype.weight = '70kg'
    Person.prototype.eat = function () {
        console.log('我会吃饭');
    }
    function Student() {
        // 借用构造函数实现对实例属性的继承
        Person.call(this);
    }
    // 原型链实现对原型属性和方法的继承
    Student.prototype = new Person();
    Student.prototype.contructor = Student;
    let stu1 = new Student();
    /* console.log(stu1);
    console.log(stu1.weight); */
    stu1.eat()



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