JavaScript 中带有 `super` 关键字的多级对象继承
Multi-level object inheritance in JavaScript with `super` keyword
我想将多个对象合二为一。 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.create(layer2, addon);
layer3.runBusinessLogic(); // throws "TypeError: layer3.runBusinessLogic is not a function"
我希望 layer3.runBusinessLogic(..)
调用 base.runBusinessLogic(..)
并且自身仍然有可调用的 unrelatedExtraMethod
。
如何使 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()
我想将多个对象合二为一。 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.create(layer2, addon);
layer3.runBusinessLogic(); // throws "TypeError: layer3.runBusinessLogic is not a function"
我希望 layer3.runBusinessLogic(..)
调用 base.runBusinessLogic(..)
并且自身仍然有可调用的 unrelatedExtraMethod
。
如何使 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()