MJingv / jehol-person-blog

Jehol's Blog 🙋 (hexo+react)
https://mjingv.github.io/JeholBlog/
0 stars 1 forks source link

继承相关 #8

Open MJingv opened 5 years ago

MJingv commented 5 years ago

继承

参考资料

  1. 六种继承方法

  1. class 只是语法糖,本质还是函数

function Parent(value) { this.val = value; }

Parent.prototype.getVal = function () { console.log(this.val); };

function Child(value) { Parent.call(this, value); //super }

Child.prototype = new Parent(); //extends

let child = new Child(1);

child.getVal();//1 console.log(child instanceof Parent);//true


- 寄生组合继承

> 1. 优化:组合继承缺点在于继承父类函数时调用了构造函数
> 2. 核心:**将父类的原型赋值给了子类,并且将构造函数设置为子类**,这样既解决了无用的父类属性问题,还能正确的找到子类的构造函数。
```js

function Parent(value) {
    this.val = value;

}

Parent.prototype.getVal = function () {
    console.log(this.val);
};

function Child(value) {
    Parent.call(this, value); //super
}

// Child.prototype = new Parent();

Child.prototype = Object.create(Parent.prototype, {
    constructor: {
        value: Child,
        enumerable: false,
        writable: true,
        configurable:true,
    }
});

let child = new Child(1);
child.getVal();//1
console.log(child instanceof Parent);//true

class Parent { constructor(value) { this.val = value; }

getVal() {
    console.log(this.val);
};

}

class Child extends Parent { constructor(value) { super(value); this.val = value; }

}

let child = new Child(1); child.getVal(); //1 console.log(child instanceof Parent);//true