JavaScript原型链继承

58 阅读1分钟

继承-直接继承prototype属性

<script>

    function Person(){
    }

    Person.prototype.foot = 2;

    Person.prototype.head = 1;

    function Student(name,no){

        this.name=name;

        this.no=no;

    }
    //通过直接继承prototype属性

    //相较第一种,不用执行和建立Person实例,节省内存

    Student.prototype = Person.prototype;

    //手工理顺一下继承链

    Student.prototype.constructor = Student;

    //每个实例的prototype对象都有一个constrctor属性

    //alert(Student.prototype.constructor);
    //继承链紊乱

    var stu1 = new Student("张三","s001");

    alert(stu1.constructor);

    alert(stu1.name);

    alert(stu1.no);

\


    alert(stu1.foot);

    alert(stu1.head);

\


    //缺点:把父类Person的constructor也同步改掉了

    alert(Person.prototype.constructor);

\


</script>

继承-prototype属性

<script>

    function Person(){

        this.foot = 2;

        this.head=1;

    }

    function Student(name,no){

        this.name=name;

        this.no=no;

    }

    //通过prototype属性实现继承
    //Student的prototype属性指向一个Person实例的写法,相当于完全删除了prototype原先的值,赋了一个新值
    Student.prototype = new Person();
    //手工理顺一下继承链
    Student.prototype.constructor = Student;
    //每个实例的prototype对象都有一个constrctor属性
    //alert(Student.prototype.constructor);
    //继承链紊乱
    var stu1 = new Student("张三","s001
    alert(stu1.
    alert(stu1
    alert(stu1.no);
    alert(stu1.foot);

    alert(stu1.head);
</script>

继承-使用空对象作为中介

<script>

    function Person(){} 
   Person.prototype.foot = 2;
    Person.prototype.head = 1;
    function Student(name,no){
        this.name=name;
        this.no=no;
    }
    //F空对象,几乎不占内存
    var F= function(){};
    F.prototype = Person.prototype;
    Student.prototype = new F();
    var stu1 = new Student("张三","s001");
    Student.prototype.constructor = Student;
     /*alert(stu1.constructor);
    alert(stu1.name);
    alert(stu1.no);
    alert(stu1.foot);
    alert(stu1.head);*/
    //F空对象作为中介解决了如下缺点
    // 缺点:把父类Person的constructor也同步改掉了
    alert(Person.prototype.constructor);
\