简体   繁体   English

JavaScript 中的多级 object inheritance 带有 `super` 关键字

[英]Multi-level object inheritance in JavaScript with `super` keyword

I want to compose multiple objects into one.我想将多个对象组合成一个。 The super keyword should call corresponding parent object method. super关键字应该调用对应的父 object 方法。 If parent's method is not present, it should call next parent's method and so on.如果 parent 的方法不存在,它应该调用下一个 parent 的方法,依此类推。

Example code that throws:抛出的示例代码:

var base = {
  runBusinessLogic() {
    console.log('BASE');
  }
}

var concrete = {

  unrelatedExtraMethod() {
  }
}

var addon = {
  runBusinessLogic() {
    super.runBusinessLogic(); // I expect this super call to call base.runBusinessLogic(..)
    console.log('ADDON');
  }
}

var layer2 = Object.setPrototypeOf(concrete, base);
var layer3 = Object.create(layer2, addon);

layer3.runBusinessLogic(); // throws "TypeError: layer3.runBusinessLogic is not a function"

I expect the layer3.runBusinessLogic(..) to call base.runBusinessLogic(..) and still have callable unrelatedExtraMethod on itself.我希望layer3.runBusinessLogic(..)调用base.runBusinessLogic(..)并且本身仍然有可调用的unrelatedExtraMethod

How to make the super keyword work as outlined?如何使super关键字按概述工作?

 var base = { runBusinessLogic() { console.log('BASE'); } } var concrete = { unrelatedExtraMethod() { } } var addon = { runBusinessLogic() { super.runBusinessLogic(); // I expect this super call to call base.runBusinessLogic(..) console.log('ADDON'); } } var layer2 = Object.setPrototypeOf(concrete, base); var layer3 = Object.setPrototypeOf(addon, layer2); // change this layer3.runBusinessLogic()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM