JS(JavaScript)中的继承——分析总结(附源码)

继承: 就是子类去继承父类的公有属性和私有属性;
继承的特点: 可以拥有父类的公有属性和私有属性;


继承的分类:

  1. 原型继承
  2. call继承
  3. 组合式继承
  4. ES6中的继承

  • 原型继承:(关键代码:Child.prototype = new Parent;
  • 特点可以继承父类的公有属性;
function Parent() {  // 父类
        this.x = 100;
    }
    Parent.prototype.getX = function () {
        return this.x;
    }
    function Child() {  // 子类
        this.y = 200;
    }
    Child.prototype = new Parent; // (关键代码)让子类的原型指向父类对象
    Child.prototype.getY = function () {
        return this.y;
    }
    var c1 = new Child();
    console.log(c1.x); // x是继承父的x
    console.log(c1.getX()); // getX是继承父的x
    console.log(c1.y); // getX是继承父的x
    console.log(c1.getY()); //这个是自己写的方法
  • call继承:(关键代码:Parent.call(this);
  • 特点:只能继承父类的私有属性
function Parent() {  // 父类
        this.x = 100;
    }
    Parent.prototype.getX = function () { // 子类
        return this.x;
    }
    function Child() {
        // 1) 让this指向一个空对象
        // 2)执行父类中的代码(为这个新对象添加属性)
        // 3)返回这个空对象
        Parent.call(this);//此时call改变了Parent中的this指向,让this指向一个空对象,然后执行Parent中的this.x = 100;让空对象中有属性值,此时的属性值就是父类中继承过来的;
        this.y = 200;
    }
    var c1 = new Child();
    console.log(c1.x);
  • 组合式继承:(关键代码:Parent.call(this);Child.prototype = Object.create(Parent.prototype);
  • 特点继承了父类的公有属性以及私有属性;
function Parent() {  // 父类
        this.x = 100;
    }
    Parent.prototype.getX = function () { 
        return this.x;
    }
    function Child() {
        Parent.call(this); // 继承父的私有属性
        this.y = 200;
    }
    // Child.prototype = Parent.prototype;  继承父类公有属性,这样写不好,因为你如果改变子类的原型对象中的方法,父类中的也会改变,说白了,这样写,子类会影响父类;
    //最好的解决办法就是:
    //给父类的原型对象再copy一份,这样子类既继承了父类的公有方法也不会影响父类;如下:
    Child.prototype = Object.create(Parent.prototype);//给Object的原型对象中增加父类的原型对象,
    //最好手动修改一下Child原型对象上的constructor的指向;
    Child.prototype.constructor = Child; //手动修改constructor的指向;
    var c = new Child();
    console.log(c.x); //此x为父类的私有属性
    console.log(c.getX()) //此getX为父类的公有属性
  • ES6中的继承:(关键代码:super();extends
  • 特点:继承父类的私有属性和公有属性;
 class Parent{
        constructor() { //相当于自己的私有属性
            this.x = 100;
        }
        getX(){ //相当于公有属性;
            return this.x;
        }
    }
    class Child extends Parent{ //extends继承了父类的公有属性;
        constructor() {
            super(); // 类似于前面我们所说的call继承(继承了父类的私有属性)
            this.y = 200; //子类的私有属性
        }
        getY(){ //子类的公有属性
            return this.y
        }
    }
    var child = new Child();
    console.log(child.x);
    console.log(child.getX());

猜你喜欢

转载自blog.csdn.net/qq_44830054/article/details/107568738
今日推荐