原型链继承

52 阅读1分钟
 script>
    /* 父类 */
    function Person(){
        // this.head = 1;
        // this.foot = 2;
    }
    Person.prototype.head = 1;
    Person.prototype.foot = 2;
    /* 子类 */
    function Student(){
        this.name ='zhangsan';
        this.no = '9587';
    }
    /*  
Student的prototype指向一个Person的实例
    */
   /* 
    Student的prototype属性指向一个Person实例的写法,相当于完全删除了prototype原先的值,赋了一个新值,所以要为新的prototype对象加上constructor属性,并将这个属性指回原来的构造函数
   */
  /* new出来的是一个实例化对象 覆盖 到构造函数Student的原型上 */
//    Student.prototype = new Person();
//    /* constructor 构造器 */
//    Student.prototype.constructor = Student;
//    let stu1 = new Student();
//    console.log(stu1);
//    /* 实例化出来的对象 本身是没有foot属性,通过原型链找到了原型里面的属性foot */
//    document.write(stu1.foot);

   /* 构造函数 */
//    function A(){
//        /* 构造函数内部的属性 */
//        this.car = '奔驰'
//    }
//    /* 通过new 实例化出了一个对象a */
//    let a = new A()
//    console.log(a);

/* 直接继承prototype */
/* 由于Person对象中,不变的属性都可以直接写入Person.prototype。 */
    // console.log( Person.prototype);
    Student.prototype = Person.prototype;
    Student.prototype.constructor = Student;
    let stu1 = new Student();
    // console.log(stu1);
    /* 继承之后通过原型链找到Student的原型下面的head属性 */
    // document.write(stu1.head);
    /* 按道理来说,子类是不能改变父类 */
    Student.prototype.car = '本田';
    console.log(Person.prototype)
    /* 
        优点:效率比较高(不用执行和建立Person的实例了)
缺点:Student.prototype和Person.prototype现在指向了同一个对象,任何对Student.prototype的修  改,都会反映到Person.prototype

    */

</script>