搞晕js继承

组合式继承

        // 父类
        function Person() {
            // 父类的属性
            this.hobbies = ['music', 'reading']
        }
        // 父类的函数
        Person.prototype.say = function() {
            console.log('person say')
        }
        // 子类
        function Student() {
            // 继承父类的属性(构造函数继承)
            Person.bind(this)();
            // Person.call(this);
            // Person.apply(this);  一个意思

            // 子类自己的属性
            this.score = 90;
        }
        // 继承父类的函数(原型链继承)
        Student.prototype = new Person();
        // 所有涉及到原型链继承的继承方式都要修改子类构造函数的指向,否则子类实例的构造函数会指向父类。
        Student.prototype.constructor = Student;
        // console.log(Student.prototype.constructor)
        // 子类自己的函数
        Student.prototype.run = function() {
            console.log('student run');
        }
        // new两个实例
        var stu1 = new Student();
        var stu2 = new Student();
        // 实例的属性独立
        stu1.hobbies.push('aaa');
        console.log(stu1, stu2);
        // 实例的函数共享
        console.log(stu1.say === stu2.say);
        console.log(stu1.run === stu2.run);

寄生组合式继承

        // 实现继承的核心函数
        function inheritPrototype(subType, superType) {
            function F() {};
            //F()的原型指向的是superType
            F.prototype = superType.prototype;
            //subType的原型指向的是F()
            subType.prototype = new F();
            // 重新将构造函数指向自己,修正构造函数
            subType.prototype.constructor = subType;
        }
        // 父类
        function Person() {
            // 父类的属性
            this.hobbies = ['music', 'reading']
        }
        // 父类的函数
        Person.prototype.say = function() {
            console.log('person say')
        }
        // 子类
        function Student() {
            // 继承父类的属性(构造函数继承)
            Person.call(this);
            // Person.apply(this);  一个意思

            // 子类自己的属性
            this.score = 90;
        }
        // 继承父类的prototype
        inheritPrototype(Student, Person);
        // 子类自己的函数
        Student.prototype.run = function() {
            console.log('student run');
        }
        // new两个实例
        var stu1 = new Student();
        var stu2 = new Student();
        // 实例的属性独立
        stu1.hobbies.push('aaa');
        console.log(stu1, stu2);
        // 实例的函数共享
        console.log(stu1.say === stu2.say);
        console.log(stu1.run === stu2.run);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容