JS中的继承总结

时间:2020-03-27
本文章向大家介绍JS中的继承总结,主要包括JS中的继承总结使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

面向对象特性:封装,继承,多态

继承,类与类之间的关系,面向对象的语言的继承是为了多态服务的,
js不是面向对象的语言,但是可以模拟面向对象.模拟继承.为了节省内存空间

继承:

原型作用: 数据共享 ,目的是:为了节省内存空间,
原型作用: 继承 目的是:为了节省内存空间

方式一:原型继承:改变原型的指向

    function Person(age) {
        this.age = age;
    }
    Person.prototype.eat = function() {
        console.log("人正在吃东西");
    }

    function Student(sex) {
        this.sex = sex;
    }
    Student.prototype = new Person(12);
    Student.prototype.study = function() {
        console.log("学生在学数学");
    }
    var stu = new Student("女");
    stu.eat();
    stu.study();

方式二:借用构造函数继承:主要解决属性的问题

     function Person(name, age) {
            this.name = name;
            this.age = age;
        }
        Person.prototype.sayHi = function() {
            console.log("say,hi");
        }

        function Student(name, age, score) {
            Person.call(this, name, age, score);
            this.score = score;
        }
        var stu = new Student("小白", 20, 130);
        var stu2 = new Student("小乐", 23, 110);
        console.log(stu.name + stu.age + "==" + stu.score);
        console.log(stu2.name + stu2.age + "==" + stu2.score);
        stu.sayHi(); /* call方式不能继承父级的方法 */

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

既能解决属性问题,又能解决方法问题

        function Animate(style, sex) {
            this.style = style;
            this.sex = sex;
        }
        Animate.prototype.sleep = function() {
            console.log("要去睡觉了");
        }

        function Dog(style, sex, name) {
            Animate.call(this, style, sex);
            this.name = name;
        }
        Dog.prototype = new Animate();
        var dog = new Dog("藏獒", "公的", "大熊");
        console.log(dog.style, dog.sex, dog.name);
        dog.sleep();    


方式四:拷贝继承:就是把对象中需要共享的属性或者犯法,直接遍历的方式复制到另一个对象中

        function Person() {}
        Person.prototype = {
            // constructor: Person,
            name: "小白",
            sex: "女",
            age: 21,
            sleep: function() {
                console.log("可以睡觉了");
            }
        }
        var stu = {};
        for (var key in Person.prototype) {
            stu[key] = Person.prototype[key];
        }
        console.log(stu)        

原文地址:https://www.cnblogs.com/qtbb/p/12582624.html