Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
130 views
in Technique[技术] by (71.8m points)

javascript - Multiple classes that have a different name but extends the same class

I have for example this class:

abstract class MyClass {
  abstract myProp: number;

  constructor() {
    // Some code
  }
}

So I want to create multiple classes that extends this class. But I don't want to repeat it multiple times as I will have a lot of classes. So the purpose is that each class has a different name and myProp.

For example:

class FirstClass extends MyClass {
  myProp = 1;
  constructor() {
    super();
    // Some code
  }
}

class SecondClass extends MyClass {
  myProp = 2;
  constructor() {
    super();
    // Some code
  }
}

So I want to generate these classes (with for example a function) but the problem is that I will have to use the new keyword. So the usage for each of these classes should be like this:

const myConst = new FirstClass();
const myConst2 = new SecondClass();

I hope this makes some sense. I just don't want to repeat every class because it has a different name and myProp.

question from:https://stackoverflow.com/questions/65946853/multiple-classes-that-have-a-different-name-but-extends-the-same-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can create classes through a function that returns an anonymous class.

const createClass = ( prop: number ) => {
    return class extends MyClass {
        myProp: number;

        constructor () {
            super();
            this.myProp = prop;
        }
    }
}

const FirstClass = createClass(1);

const x = new FirstClass();
console.log(x.myProp);

Or check out the answers to these questions for ideas:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...