JavaScript原型继承

 //原型继承主要是继承构造函数中的原型(改变原型指向) 在子类构造函数与父类构造函数中有相同的属性时父类无法覆盖子类
        function Person(age,sex){
            this.age=age;
            this.sex=sex;
        }
        Person.prototype.Sleep=function(){
            console.log("睡觉");
        }
        Person.prototype.eat=function(){
            console.log("吃饭");
        }

        function Student(score){
           this.score=score;
           this.sex="男";
        }
        //原型改变后无法使用
        student.prototype.like=function(){
            console.log("学习");
        }

        //使用原型方法继承
        Student.prototype=new Person(18,"女");
        //在原型改变后再次使用原型
        student.prototype.like=function(){
            console.log("玩游戏");          
        }

        var student=new Student(120);
        student.Sleep();//睡觉
        student.eat();//吃饭
        student.like();//玩游戏; 原型改变后无法使用
        console.log(student.age+"\n"+student.sex);//指向Person的age,sex;如果原对象有,则调用原对象       
        console.log(student.score);
posted @ 2021-10-23 19:03  yongerbingxuan  阅读(37)  评论(0)    收藏  举报