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

js 中多重继承的实现 #21

Open
negativeentropy9 opened this issue Aug 18, 2019 · 0 comments
Open

js 中多重继承的实现 #21

negativeentropy9 opened this issue Aug 18, 2019 · 0 comments
Labels

Comments

@negativeentropy9
Copy link
Owner

js 中多重继承的实现

比较好的继承方式

原型式借用构造组合继承

function object (o) {
    function F () {}
    F.prototype = o;

    return new F();
}

function inheritPrototype (Sub, Super) {
    var proto = object(Super.prototype);
    proto.constructor = Sub;
    Sub.prototype = proto;
}

function Super () {

}

function Sub () {
    Super.call(this);
}
inheritPrototype(Sub, Super);

下面我们借用 原型式借用构造组合继承 来实现多重继承

function A() {
  this.class = 'A';
}

A.prototype.sayClass = () => {
  console.log('debug-sayClass', this.class);
}

function B () {
  this.name = 'B';
}

B.prototype.sayName = () => {
  console.log('debug-sayName', this.name);
}

function C () {
  A.apply(this);
  B.apply(this)
  this.type = 'C';
}

C.prototype = Object.create(Object.assign({}, A.prototype, B.prototype));

var c = new C();

c.sayClass();
c.sayName();

参考

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