如何有条件地为我的子类选择基类?

问题描述 投票:0回答:4

事情是这样的。我有一个名为 A 的主课。 我希望这门课能扩展B类。

class A extends B {}

但事实上,我希望 B 类在特定条件下扩展 C、D 或 E:

class B extends B1 {}

class B extends B2 {}

class B extends B3 {}

所以 B 类将是一个“假”类,只是为了检查条件然后扩展正确的类。 在决赛中,结果将是相同的:

class A extends B1 {}

class A extends B2 {}

class A extends B3 {}

我知道这在 PHP 中是可能的,例如使用抽象类或包装类。 但如何在 JavaScript ES6 中做到这一点?

谢谢

javascript class extends es6-class
4个回答
5
投票

奇怪,但有可能:

class subClassFirst {

  report() {
    console.log(`Extended ${this.name} from the first class`);
  }
}

class subClassSecond {

  report() {
    console.log(`Extended ${this.name} from the second class`);
  }
}

class subClassThird {

  report() {
    console.log(`Extended ${this.name} from the third class`);
  }
}

function classCreator(condition) {
  let sub;
  switch (condition) {
    case 'first':
      sub = subClassFirst;
      break;
    case 'second':
      sub = subClassSecond;
      break;
    case 'third':
      sub = subClassThird;
      break;
  }

  return (class extends sub {
    constructor(name) {
      super();
      this.name = name;
    }
  });
}

let myClass;

myClass = classCreator('first');
let mcf = new myClass('f');

myClass = classCreator('second');
let mcs = new myClass('s');

myClass = classCreator('third');
let mct = new myClass('t');

mcf.report();
mcs.report();
mct.report();


3
投票

我发现博客文章提供了一种简单的 es6 方法,不使用

util.inherits
https://www.mikedoesweb.com/2017/dynamic-super-classes-extends-in-es6/

这是我如何使用传递的选项来确定要扩展哪个类,然后在导出中对其进行混淆

import ClassB from '  '
import ClassA from '  '

const ext = {
   classA: ClassA, // the default
   classB: ClassB
// can do as many as you want
}


function ExtendsMyClass (opts= {}) {

  if (!new.target) {
    throw new Error('Uncaught TypeError: Class constructor Interrupt cannot be invoked without \'new\'')
  }

// one could vet opts here too including opts.extend

   class MyClass extends ext[opts.extend || 'classA'] {
    constructor(opts = {}) {
      super(opts)
   ....
    }
} // end MyClass

return new MyClass(opts)

} // end dynamic extend

export default ExtendsMyClass
export { ExtendsMyClass as MyClass }

我可能会将其放入“包装器”实用函数中,该函数也接受子类。这样一来,人们就可以动态地扩展任何类,而不是上面的一次性实现。如果设置了异步函数,甚至可以实现动态导入。


1
投票

所以 javascript 中的类实际上并不像其他语言那样以相同的经典继承方式设置,做你想做的事情的最好方法是设置你正在处理的对象的原型。有几种方法。

Object.setPrototypeOf(currentObj, newPrototype);

其中 newPrototype 是您要继承的对象。如果您想了解其内部工作原理,这里有几篇关于它的好文章。

http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md


0
投票

有一个 Node JS 函数可以实现这一点

const util = require("util");

class MySubClass {}
class MySuperClass {}

util.inherits(MySubClass, MySuperClass);
© www.soinside.com 2019 - 2024. All rights reserved.