JavaScript高级,对象继承之原型链继承

132 阅读1分钟
<script>
    //定义一个父类构造函数Person,属性包含头和脚
    function Person(){
        this.head = 1;
        this.foot = 2;
    }
    
    //定义一个子类构造函数Student,属性包含姓名和编号
    function Student(){
        this.name = "阿星";
        this.no = "9527";
    }
    
    Student.prototype = new Person(); //实例化一个Person对象,让Student的原型链指向这个实例
    Student.prototype.constructor = Student; //将Student的构造器重新指向自己,避免原型链紊乱
    
    //此时Student类已经继承Person类的属性,
    var stu1 = new Student(); //实例化一个Student对象stu1,此时可以通过stu1调出Person里面的head和foot属性
    console.log(stu1.head) //控制台会打印出结果1
    
</script>

//转载请标明出处