js 继承

206 阅读13分钟

一、什么是继承 ?

前言: 大多OO语言都支持两种继承方式: 接口继承和实现继承 ,而ECMAScript中无法实现接口继承,ECMAScript只支持实现继承,而且其实现继承主要是依靠原型链来实现,下文给大家技术js实现继承的六种方式

二、继承的方法总结

  • 原型继承

  • 构造函数继承(call继承)

  • 冒充对象继承

  • 实例继承

  • 组合继承

  • __proto__继承

  • extends继承(ES6) super关键字使用

三、一一分析

1.原型继承:<SonClass.prototype = new FatherClass(param1, param2,..))>

var A = function (x, y) {
   var num = 10;  //函数作为普通函数执行,变量
   this.x = x;  //实例对象增加的私有属性
   this.y = y;
   this.getX = function() {    //实例私有的方法
      console.log(this.x); 
 };
};
A.prototype.getX = function () {   //原型上共有的方法
   console.log(this.x);  
};
 A.prototype.write = function() {
    console.log('write-js');
 };
A.tools = {       //函数最为对象使用的,对象.属性 = 属性名
   getName: function() {
   },
  x: 10
}

var B = function (x, y) {
   this.x = x;
   this.y = y;
};
 B.prototype = new A(10, 20);
 B.prototype.constructor = B;   //***因为你把天生的prototype对象替换了,所以constructr你必须手动指向他本身,否则就指向了A的constructor
 B.prototype.getY = function () {
     console.log(this.y);
};



var b1 = new B(1, 2);
var b2 = new B('JS','CSS');
console.log(b1);
console.log(b1 instanceof B); //true 是子类的实例
console.log(b1 instanceof A); //true  是父类的实例
console.log(b1.hasOwnProperty('getX'));  //false 不是私有的属性(原型上)
console.log(b1.hasOwnProperty('getY'));  //false   不是私有的属性(原型上)
console.log(B.prototype.constructor === B);   //true
console.log(b1.__proto__.__proto__.getX === A.prototype.getX); //true
// 先找到自己类的原型,在通过自己类原型的.__proto__指向父类的原型, 因为 B.prototype = new A() ,B的原型就是A的一个实例么
//b1: {x: 1, y: 2}
//   __proto__  B.prototype  {x: 10, y: 20, getY: function(){} }
//   __proto__  A.prototype {getX: function(){} }


b1.getX = function () {     //这也是在b1的内存空间增加的私有方法。和b2无关
console.log('getX-prtive');
};

b1.__proto__.getX = function () {   //这个是在b1所属类的原型上增加的方法,是共享的和,所以和b2有关系
console.log('getX-common')
};

b2.getX(); // getX-common
console.log(b1.getX === b2.getX);  //b1的私有方法getX和b2共有属性方法比较 , <原型链机制查找>
console.log(b1.__proto__.getX === b2.getX); //b1和b2的getX都是共有的方法

b1.name = 'clh';  //给自己开辟的空间增加的私有属性 (***)
console.log(b2.name);

b1.__proto__.printX = function () {
console.log(this.x);
};

b2.printX();   //JS    上面那条代码在b1的类的原型上增加了一个printX方法,这里b2肯定会访问到,b2执行这个函数,this肯定是b2,所以 b2.x = JS

b1.__proto__.__proto__.init = function () {  //这是在给父类A的原型上增加一个init方法 
console.log('init-function');
};

console.log(b1.init === b2.init);  //true
console.log(b1.init === A.prototype.init);  //true


b1.__proto__.__proto__.change= function() {  //在父类A的原型上增加一个方法
    alert('chagne-getX');
};

b2.change(); //弹出 'change-getX' 调用父类A的原型的方法

b1.__proto__.__proto__.write = function() {   //*** 子类从写父类原型上的方法
    console.log('write-css');
};

b2.write();  // 'write-css'   原型链查找机制,找到父类A的原型上的write方法



 特点:
 核心:  拿父类实例来充当子类原型对象, (把父类的私有属性克隆一份,放到子类的原型上,父类的共有属性通过子类的原型上的__ptoto__查找到)
1. 非常纯粹的继承关系,实例是子类的实例,也是父类的实例
2. 父类新增原型方法/原型属性,子类都能访问到
3.简单,易于实现
缺点:

要想为子类新增属性和方法,必须要在new A()这样的语句之后执行,不能放到构造器中
无法实现多继承
来自原型对象的引用属性是所有实例共享的(详细请看附录代码: 示例1)
创建子类实例时,无法向父类构造函数传参

2.构造函数继承(call继承)(<A.call(this[,param1, param2,...])>

var A1 = function (name, age) {
   var num = 10;
   this.name = name;
   this.age = age;
};
A1.prototype.getName = function () {
   console.log('A-getName');
};

var A2 = function () {
   this.x = 10;
};
 A2.prototype.getX = function(() {
    console.log(this.x);
 };

var A3 = function () {
   this.y = 20;
};
 A3.prototype.getY = function(() {
    console.log(this.y);
 };

  var B1 = function (name, age) {
  A1.call(this, name, age);   //this是,B1类的一个实例对象, 把父类的私有属性性拷贝一份,放到这个实例的私有属性上
  A1.apply(this,arguments); //apply****继承
  A2.call(this);  //继承类A2的私有方法,放到B1实例对象的私有属性中
  A3.call(this);   //继承类A3的私有方法 ,放到B1实例对象的私有属性中
};

B1.prototype.getName = function () {
  console.log(this.name);
};
B1.prototype.getAge = function () {
   console.log(this.age);
};

var b1 = new B1('clh', 25);
console.log(b1);

console.log(b1 instanceof B1); //true  是子类的实例
console.log(b1 instanceof A1); // false 不是父类的实例
console.log(b1.getName === b1.__proto__.getName); //true 
console.log(b1.getName === b1.__proto__.__proto__.getName);    // false 后面那个是B1类原型上的.__prtot__, 那么原型是对象,所以是Object的实例,所以指向Object原型的getName,没有返回undefiend

 特点:

1. 解决了1中,子类实例共享父类引用属性的问题
2. 创建子类实例时,可以向父类传递参数
3. 可以实现多继承(call多个父类对象)
缺点:

1. 实例并不是父类的实例,只是子类的实例
2. 只能继承父类的实例属性和方法,不能继承原型属性/方法
3. 无法实现函数复用,每个子类都有父类实例函数的副本,影响性能*/

3.冒充对象继承(拷贝继承)(<A.call(this[,param1, param2,...])>

var A2 = function (color, fontSize) {
    this.a = 10;
    this.b = 20;
    this.name = 'clh';
    this.getName = function () {
         console.log(this.getName);
    };
};

A2.prototype.printA = function () {
  console.log(('A2-prototype.printA'));
};

var A3 = function (x, y) {
  this.x = x
  this.y = y;
};
A3.prototype.getX = function () {
   console.log(this.x);
};


var B2 = function (cont) {
var objA = new A2('#ff0', '30px');   //自己创建一个对象,把父类的私有和共有属性/方法拿过来,进行遍历,放到子类的 私有属性中
var objB = new A3(1, 2);
for (var key in objA) {      //A2类
    this[key] = objA[key];   // this.prototype[key] = obj[key]  这是放到子类的共有属性中,把父类的私有和共有属性
}

for (var key in objB) {   //A3类
    this[key] = objB[key];
}


this.write = cont; //在增加自己传进来的属性
};

B2.prototype.write = function () {
  console.log('wait-JS');
};
B2.prototype.printA = function () {
   console.log('B2-prototype.printA');
};

var b2 = new B2('CSS+DIV');
console.log(b2);
console.log(b2 instanceof B2);   // true 是子类的实例
console.log(b2 instanceof  A2);   // false 不是父类的实例
console.log(b2.hasOwnProperty('name')); //true 是私有属性
console.log(b2.hasOwnProperty('printA')); //true 是私有属性

b2.printA(); //  'A2-prototype.printA'  私有属性的printA(),也就是继承A2原型上的printA方法
b2.__proto__.printA(); //  'B2-prototype.printA'&emsp;直接找到B2原型上的printA方法

特点:

 1. 支持多继承
缺点:

1.  效率较低,内存占用高(因为要拷贝父类的属性)
2. 无法获取父类不可枚举的方法(不可枚举方法,不能使用for in 访问到)*/

4.实例(call继承)(<A.call(this[,param1, param2,...])>

var A3 = function (name, color) {
   this.name = name;
   this.color = color;
   this.x = 1;
   this.y = [1,2,3];
   this.getY = function () {
     console.log('A-pritive-getY');
   }
};
A3.prototype.getY = function () {
   console.log('A-common-getY');
};

var B3 = function (name, color) {
  var obj = new A3(name ,color);
  obj.x = 'JS继承';
  return obj;
};

B3.prototype.getColor = function () {
  console.log('B-common-getColor');
};

var b3 = new B3('clh', 'red');
console.log(b3);
console.log(b3 instanceof B3);  //false  因为他不是B3的实例,所以访问不到B3原型上的属性和方法
console.log(b3 instanceof A3);  //true  是A3的实例
console.log(b3.getY === A3.prototype.getY); // false
console.log(b3.getY.__proto__.getY === A3.prototype.getY); //false
console.log(b3.getY === A3.prototype.getY); //false
console.log(b3.hasOwnProperty('getY')); //true



特点:

 不限制调用方式,不管是new 子类()还是子类(),返回的对象具有相同的效果
缺点:

实例是父类的实例,不是子类的实例
不支持多继承*/

5.组合继承 < 原型链继承 + 构造函数继承(call继承)>

var Animate = function (name, color, age, food) {
   this.name = name;
   this.color = color;
   this. age = age;
   this.eat = function (food) {
       console.log(this.name + '喜欢吃' + food);
   };
  this.write = function() {    //私有方法 write
         console.log('wirte-js');
  };
};

Animate.prototype.write = function() {   //共有方法write
   console.log('write-css');
 }
Animate.prototype.sleep = function (sleep) {
    console.log(this.name + '喜欢在' + sleep + '睡觉');
};
Animate.prototype.running  = function (runMethod) {
   console.log(this.name + '跑的方法' + runMethod);
};


var Dog = function (name, color, age, food) {
   Animate.call(this, name, color, age, food);  //构造函数继承父类的私有属性和方法
};

Dog.prototype = new Animate(); //继承父类的私有属性和私有方法放到这个类的原型上
Dog.prototype.constructor = Dog;  //强制constructor指向自己,否则原型链会混乱了
Dog.prototype.play = function (plays) {
    console.log(this.name + '喜欢玩' + plays);
};
Dog.prototype.write = function() {
     console.log('write-html');
};

var dog1 = new Dog('小狗', 'red', 23, '骨头'); 
console.log(dog1);
console.log(dog1 instanceof Dog); //true  是子类的一个实例
console.log(dog1 instanceof  Animate);  //true 是父类的一个实例

console.log(dog1.sleep === Animate.prototype.sleep); //true 第一个找到自己原型上的sleep方法,也就是原型继承过来的父类的原型sleep, 第二个是父类原型上的sleep方法
console.log(dog1.__proto__.__proto__.sleep === Animate.prototype.sleep); //true    自己子类原型.__prtoto__指向父类的prototype  所以为true
dog1.sleep('爬在地上');
dog1.running('四条腿');

dog1.sleep = function() {   //修改自己类原型上的sleep方法
        alert('ok'); 
};

dog1.sleep(); // 'ok'

dog1.__proto__.__proto__.sleep = function() {   //修改父类原型上的sleep方法
       alert('chagne-sleep-method');
};
var  animate1 = new Animate();
animate1.sleep();   // 'chagne-sleep-method'
dog1.__proto__.__proto__.sleep(); //'chagne-sleep-method'

dog1.write ();  //  ’write-js' 私有属性的write方法
dog1.__proto__.write();   //’write-html'  共有属性子类原型上的write方法, 这里因为你首先进行了原型继承,子类原型上有一个write方法,你又给这原型对象增加了一个write方法,他肯定会把继承过来的write方法给覆盖了,所以输出结果为'write-html'
dog1.__proto__.__proto__.write();   // ’write-css‘  父类原型上的write方法

特点:

 1. 弥补了方式2的缺陷,可以继承实例属性/方法,也可以继承原型属性/方法
 2. 既是子类的实例,也是父类的实例
 3. 不存在引用属性共享问题
 4. 可传参
 5. 函数可复用
 6. 可以实现多继承(call)

缺点:

 1.  调用了两次父类构造函数,生成了两份实例(子类实例将子类原型上的那份屏蔽了)
 

6.寄生组合继承( < 原型链继承 + 构造函数继承(call继承)) (利用空对象作为中介)

var AClass = function (name, age) {
   this.name = name;
   this.age =age;
   this.getAge = function () {
       console.log(this.age);
   };
   this.getName = function () {

    };
};

AClass.prototype.getName =function () {
    console.log(this.name);
};


var BClass = function (name, age) {
    AClass.call(this, name, age);
   this.height = '180cm';
};
 
 // 其实这样做的目的是原型只继承父类原型上的东西
function extend(Child, Parent) {
    var F = function(){}; //空对象
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
    Child.uber = Parent.prototype;   //为子对象设一个uber属性,这个属性直接指向父对象的prototype属性, 这等于在子对象上打开一条通道,可以直接调用父对象的方法。这一行放在这里,只是为了实现继承的完备性,纯属备用性质
}
extend(BClass, AClass);
BClass.prototype.getHeight = function () {

};

var bclass1 = new BClass('clh' ,25);
var bclass2 = new BClass('wd' ,23);
console.log(bclass1);
console.log(bclass1 instanceof BClass);  //true 是子类的实例
console.log(bclass1 instanceof AClass);  //true  是父类的实例


console.log(bclass1.getHeight === bclass2.getHeight);  // true都是子类原型上的getHeight
console.log(bclass1.getName === AClass.prototype.getName); // false 第一个是自己类上原型上的getName,  第二个是父类原型上的getName ,肯定不一样
console.log(bclass1.__proto__.__proto__.getName === AClass.prototype.getName); //true  都是父类原型上的getName方法

 特点:
 1. 堪称完美
 缺点:

 1.  实现较为复杂

7.proto继承 <arguments.proto = Array.prototype>

  function sum() {
     console.log(arguments instanceof  Array);   //false, 不是数组,不可以使用数组提供的方法
     arguments.__proto__ = Array.prototype;      //在中间加了一层,强制将__proto__指向了数组的原型
     console.log(arguments instanceof Array);  // true  在数组了,可以用数组的方法
     console.log(arguments.slice()); // [1,2,3,1] 克隆一份数组
  }
  
sum(1,2,3,1);

8.ES6继承 extens, super关键字

  • 使用extends继承, super关键字
  • super必须在之类构造函数之前使用
  • 子类继承父类静态方法
 继承核心: ES5语法糖
     ES5 的继承,实质是先创造子类的实例对象this,然后再将父类的方法添加到this上面(Parent.apply(this))。ES6 的继承机制完全不同,实质是先将父类实例对象的属性和方法,加到this上面(所以必须先调用super方法),然后再用子类的构造函数修改this。
 1.语法:
  class 子类 extens 父类 {
      super(); // ==>去继承父类的方法
      this.x = x;
  }
  
 2.super关键字用法
 
   - 1) super作为函数调用时,代表父类的构造函数
   - 2) super作为对象时,在普通方法中,指向父类的原型对象 (在子类的原型方法中)
   - 3) super作为对象时,用在子类的静态方法中,代表父类本身
   
   ===>> 
   - 4)在子类的静态方法中,super调用父类的静态方法的时候,静态方法里面的this指向子类,而不是父类
   - 5)在子类的原型方法中,super调用父类的原型方法的时候,父类的原型方法里面的this指向子类的实例,而不是父类
   - 6)子类的构造函数中super只能调用父类原型方法,并且父类原型方法里面this是子类的某个实例,不可以调用父类的静态方法
   
3.复习ES定义类

    class Animate {
       //  构造函数
       constructor(name, age) {
           // 1.==>私有属性
               this.name = name;
       }
   
       //2. ==> 原型方法
       getName() {
           return this.name;
       }
   
       //3. ==> 静态方法
       static getAge() {
           return this.age;
       }
   }
   
   Animate.color = 'white'; // 4.==> 静态属性
   

1.继承案例

    eg1: ===========================================>>
    class Animate {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    
        getName() {
            console.log('father-getName');
            return this.name;
        }
    
        static getAge() {
            console.log('getAge');
        }
    }
    
    
    class Dog extends Animate {
        constructor(name, age) {
            super(name, age); // ==> super代表子类的实例 
            this.color = 'white';
            console.log(super.getName()); // 2.==> 代表父类的原型  ==> Animate.prototype
        }
        getName() {
            super.getName();
        }
        static xx() {
            super.getAge();  // ==>> 3. super ==> 代表 Animate
        }
    }
    
    let dog1 = new Dog('土狗', 23);
    
    dog1.name; // ==> '土狗'
    dog1.getName(); // ==> 'father-getName'
    Dog.xx(); // ==>  'getAge'
  1. 子类中的super调用父类方法(原型,静态方法)的时候,父类中方法中的this指向问题
        class A {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            getX() {
                debugger
                return this.x;
            }

            static getY() {
                debugger
                return this.y;
            }
        }
        A.prototype.x = 'vue';

        class B extends A {
            constructor(x, y) {
                super(x, y);
                console.log(super.getX()); // ==> 1  //1.去继承  调用父类的原型方法getX();  父类原型上的的getX方法中的this指向子类的这个实例 
            }

            getX() {
                return super.getX();    //2.这里的super代表,父类原型 ==>> A.prototype.getX(this); 强制改变父类原型上的getX方法中的this为当前子类的实例
            }

            static getY() {
                return super.getY();  //3.这里的super代表,父类 ==>> A.getX(B); 强制改变父类静态getX方法中的this为当前子类
            }
        }
        B.y = 'jQuery';

        let a1 = new A('vue', 'react');
        let b1 = new B(1, 2);

        let x = b1.getX();
        console.log(x); // ==> 1

        let y = B.getY();
        console.log(y); // ==> 'jQuery'




        //====> 补充,
        console.dir(A);
        console.dir(B);
        console.log(B.__proto__ === A);      // ==> true  ES5 是  B.__proto__ === A.prototype
        console.log(b1 instanceof B);       // ==> true
        console.log( b1 instanceof A);      // ==> true
        console.log(b1 instanceof Object);  // ==> true

3.优化案例2 子类不用写原型方法和静态方法,全部继承父类的原型和静态方法

         class A {
           constructor(x, y) {
               this.x = x;
               this.y = y;
           }
           getX() {
               return this.x;
           }

           static getY() {
               return this.y;
           }
       }
       A.prototype.x = 'vue';

       class B extends A {
           constructor(x, y) {
               super(x, y);
               console.log(super.getX()); // ==> 1  //1.去继承  调用父类的原型方法getX();  父类原型上的的getX方法中的this指向子类的这个实例 
           }
       }
       B.y = 'jQuery';

       let a1 = new A('vue', 'react');
       let b1 = new B(1, 2);
       console.log(b1.getX()); // ==>> this问题  b1.__proto__.getX.call(b1);  b1.__proto__.getX === A.prototype.getX.call(b1)
       console.log(B.getY()); // ==>> this问题   B.__proto__.getY.call(B);   B.__proto__.getY === A.getY(B)
  1. 案例,一二三级卡片,一二三级继承卡片类的更新名称,删除...
class Card {
    updateCard(id, name = '一级卡片') {
        ajax....
    }
    
    deleteCard(id) {
        ajax...
    }
}


class OneCard extends Card {
    constructor(id, name) {
        super(id, name);
    }
}

class TwoCard extends Card {
    constructor(id, name) {
        super(id, name);
    }
}

之前继承写法:

    // 父类
    function Person(name, age) {
        this.name = name;
    }

    Person.prototype.getName = function() {
        return this.name;
    };


    // 子类
    function Student(name, skill) {
        Person.call(this, name);  // ==>>call/apply 去执行父类构造函数方法,改变里面的this为当前子类的时候,挂属性
        this.skill = skill;
    }

    Student.prototype = new Person();   // ===>> (原型链继承) 子类的原型等于父的实例,但是子类原型上的constructor覆盖掉了,待重新指向了 
    Student.prototype.constuctor = Student;   


    let student1  = new Student('clh', 'es6');

    let name =  student1.name;
    let val = student1.getName();
    console.log(name, val);  //==> clh  clh 
    

现在继承 ES6

  1. 直接继承父类的所有属性和方法 , 子类什么都不用写, 直接继承,内置改变this指向,
    class Person {
        constructor(name) {
            this.name = name;
        }

        getName() {
            return  `名字是==> ${this.name}`;
        }
    }

    class Student extends Person {

    }


    let student1  = new Student('clh', 'es6');

    let name =  student1.name;
    let val = student1.getName(); //==>> 父类原型上的方法  student1.__protot__.getName.call(student1);内部给处理了this指向问题
    console.log(name, val);  //==> clh  名字是==> clh
  1. 继承父类的属性和方法,并且增加自己的一些属性和方法,加入constructor构造函数,super去继承
        class Person {
            constructor(name) {
                this.name = name;
            }

            getName() {
                console.log('父类的getName方法');
                return `名字是==> ${this.name}`;
            }
            static fn() {
                console.log('父类的静态方法fn');
            }
        }

        class Student extends Person {
            constructor(name, skill) {
                super(name); // ===>> Person.call(this, name)
                this.skill = skill;
            }
            
            // ==> 子类的原型方法
            getName() {
                super.getName(); //===>> 父级的方法执行 (**** 把父级的代码拿过来执行了)

                // ==> todo
                console.log('子类的getName方法');
            }
            static fn() {
                super.fn();
                console.log('子类的静态方法fn');
            }
        }


        let student1 = new Student('clh', 'es6');

        let name = student1.name;
        let val = student1.getName(); // ==>  '父类的getName方法'  子类的getName方法
        student1.__proto__.__proto__.getName(); // ==>  '父类的getName方法' 
        console.log(name, val); //==> clh undefined

        Student.fn(); // ==> 子类的静态方法fn 子类的静态方法fn

3.拖拽继承案例

        //==> 拖拽类
        class Drag {
            constructor(id) {
                this.oDiv = document.querySelector(id);
                this.distX = 0;
                this.distY = 0;
                this.init();
            }

            init() {
                this.oDiv.onmousedown = function (e) {
                    this.distX = e.clientX - this.oDiv.offsetLeft;
                    this.distY = e.clientY - this.oDiv.offsetTop;

                    document.onmousemove = this.fnMove.bind(this);
                    document.onmouseup = this.fnUp.bind(this);
                    return false;
                }.bind(this); //===> 改变函数里面的this指向,这里也可以用箭头函数
            }

            fnMove(e) {
                this.oDiv.style.left = e.clientX - this.distX + 'px';
                this.oDiv.style.top = e.clientY - this.distY + 'px';
            }
            fnUp() {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }



        // ==>> 子类限制范围
        class LiemtDrag extends Drag {
            fnMove(e) {
                super.fnMove(e);  // ========>> 把父类的fnMove方法拿过来执行了 或则理解 super.fnMove.call(this, e);
                // 水平限制
                if (this.oDiv.offsetLeft <= 0) {
                    this.oDiv.style.left = 0;
                }

                // 垂直限制
                if (this.oDiv.offsetTop <= 0) {
                    this.oDiv.style.top = 0;
                }
            }
        }

        let dog1 = new Drag('#div1');
        let liemtDrag1 = new LiemtDrag('#div2');