继承(个人学习笔记)

2018-10-03  本文已影响0人  大哈QAQ

继承的发展史:

继承的发展史

1、传统模式——>原型链:

            下图是通过改变原型链的指向来实现继承(子类的原型prototype等于父类的实例):

虚线是改变指向之前的原型指向

            缺点:因为改变原型指向的同时实现继承,并初始化了属性或方法,继承过来的属性或方法都是一样的,并且无法得到实例的对应的constructor,除非手动添加,也过多继承了无用的属性(包括父类私有和共有属性和方法)。

2、借用构造函数(继承的时候不用改变原型的指向,直接调用别的构造函数的方式来为属性或方法赋值):

            //这是个反例,通过原型链继承所造成的问题

            function    Person(name,sex){

                    this.name = name;

                    this.sex = sex;

            }

            Person.prototype.say = function () { console.log("hello") };

            function    Student(score){

                    this.score = score

            }

            Student.prototype = new Person(”hello“,"boy");

            var    student1= new    Student(90);    //student1: { name:"hello",sex:"boy",score:90}

            var    student2 = new    Student(98);  //student2: { name:"hello",sex:"boy",score:98} 

            var    student3 = new    Student(100);//student3: { name:"hello",sex:"boy",score:100}

            //这样就造成了Student的所有实例部分属性或方法一样,需要手动为实例更改属性或方法才可以有不同的属性值,为了解决这个问题,我们可以通过借用构造函数实现继承

            通过call来借用构造函数:

            //改造上面的反例

             function    Student(name,sex,score){        

                    Person.call(this,name,sex);    //通过call来借用构造函数

                    this.score = score;

            }

            //借用构造函数不能继承该函数的原型对象,因此定义在改构造函数原型的方法不能被借用

3、共享原型:

共享原型实现继承

            缺点:一方改变原型都会影响到另外一方

4、圣杯模式:

圣杯模式

5、组合继承(原型继承+借用构造函数继承):

上一篇 下一篇

猜你喜欢

热点阅读