Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

六种继承 #31

Open
wuxianqiang opened this issue Jan 9, 2018 · 0 comments
Open

六种继承 #31

wuxianqiang opened this issue Jan 9, 2018 · 0 comments
Labels

Comments

@wuxianqiang
Copy link
Owner

wuxianqiang commented Jan 9, 2018

原型链继承

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
}
//B继承A
B.prototype = new A();
B.prototype.constructor = B;

利用原型让一个引用类型继承另一个引用类型的属性和方法

借用构造函数继承

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
    //B继承A
    A.call(this);
}

在子类构造函数的内部调用父类构造函数

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

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
    //B继承A
    A.call(this);
}
//B继承A
B.prototype = new A();
B.prototype.constructor = B;

原型式继承

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
}
//B继承A
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

借助原型可以基于已有的对象创建新的对象

寄生式继承

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
    //B继承A
    let obj = new A;
    for (const key in obj) {
        this[key] = obj[key]
    }
    obj = null;
}

在子类的构造函数中增加父类的属性和方法

寄生组合式继承(推荐)

function A() {
    this.a = "a";
}

function B() {
    this.b = "b";
    //B继承A
    let obj = new A;
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            this[key] = obj[key]
        }
    }
    obj = null;
}
//B继承A
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;

通过构造函数来继承属性,通过原型链来继承方法

ES6中的继承

class A {
    constructor() {
        this.a = "a"
    }
}
class B extends A {
    //B继承A
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant