欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript继承

程序员文章站 2024-03-04 09:03:05
...

JavaScript继承

方法一:通过原型实现继承

    //动物的构造函数
    function Animal(name,weight){
        this.name=name;
        this.weight=weight;
    }
    //动物的原型方法
    Animal.prototype.eat = function(){
      console.log("每天都在吃");
    };
    //狗的构造函数
    function Dog(color){
        this.color=color;
    }
    //狗的原型方法
    Dog.prototype = new Animal("哮天犬","30kg");//改变原型指向
    Dog.prototype.bite = function(){
        console.log("汪汪汪~~咬你");
    };
    //哈士奇
    function ErHa(sex){
        this.sex=sex;
    }
    ErHa.prototype = new Dog("白色");//改变原型指向
    ErHa.prototype.playHost = function(){
        console.log("玩的好开心,哈哈……");
    };

    var erHa = new ErHa("雄性");
    console.log(erHa.name,erHa.weight,erHa.color,erHa.sex);
    erHa.eat();
    erHa.bite();
    erHa.playHost();
    console.dir(erHa);

输出结果:

JavaScript继承

JavaScript继承

JavaScript继承

JavaScript继承

方法二:借用构造函数继承

    function Person(name,age,sex,weight){
        this.name=name;
        this.age=age;
        this.sex=sex;
        this.weight=weight;
    }
    Person.prototype.sayHi = function(){
        console.log("Hello!");
    };
    function Student(name,age,sex,weight,score){
        //借用构造函数
        Person.call(this,name,age,sex,weight);
        this.score=score;
    }

    var student = new Student("Tom",20,"男","60kg",100);
    console.log(student.name,student.age,student.sex,student.weight,student.score);
    console.dir(student);
    //父类中的方法不能继承,调用会报错:Uncaught TypeError: student.sayHi is not a function
    //student.sayHi();
JavaScript继承

JavaScript继承

方法三、组合继承:原型继承+借用构造函数继承

    function Person(name,age,sex,weight){
        this.name=name;
        this.age=age;
        this.sex=sex;
        this.weight=weight;
    }
    Person.prototype.sayHi = function(){
        console.log("Hello!");
    };
    function Student(name,age,sex,weight,score){
        //借用构造函数——继承属性值
        Person.call(this,name,age,sex,weight);
        this.score=score;
    }
    //改变原型指向继承,不用赋值
    Student.prototype = new Person();
    Student.prototype.eat = function(){
        console.log("食堂好多好吃的");
    };

    var student = new Student("Tom",20,"男","60kg",100);
    console.log(student.name,student.age,student.sex,student.weight,student.score);
    student.sayHi(); //可以调用父类原型方法
    student.eat();
    console.dir(student);

JavaScript继承

方法四、拷贝继承

拷贝继承:把一个对象中的属性和方法直接复制到另一个对象中(通过循环遍历赋给另一个对象)

    function Person(){

    }
    Person.prototype.name="Tom";
    Person.prototype.age=20;
    Person.prototype.sex="男";
    Person.prototype.weight="60kg";
    Person.prototype.sayHi = function(){
        console.log("Hello!");
    };

    var student=[];
    for(var key in Person.prototype){
        student[key]=Person.prototype[key];
    }

    console.log(student.name,student.age,student.sex,student.weight);
    student.sayHi(); 
    console.dir(student);

JavaScript继承

JavaScript继承

总结:

JavaScript继承

相关标签: 继承