Is it a bad practice to return a class inside the method of another class?
Example: createBlockClass method
class BlockBuilder {
constructor (methodForBlock) {
this.methodForBlock = methodForBlock;
};
createBlockClass () {
const method = this.methodForBlock.bind(this.methodForBlock);
return class Block {
constructor(title) {
this.title = title;
};
method = method;
}
}
};
const blockBuilder = new BlockBuilder(() => console.log('Hello, world!!!'));
const Block = blockBuilder.createBlockClass();
const block1 = new Block("block one");
const block2 = new Block("block two");
block1.method();
block2.method();
I need to receive a method as a parameter and add it to the block class before creating any instance
CodePudding user response:
You can use a function to create a class:
function createBlockClass(methodForBlock) {
return class Block {
constructor(title) {
this.title = title;
}
method = methodForBlock;
}
}
const Block = createBlockClass(() => console.log('Hello, world!!!'));
const block1 = new Block("block one");
const block2 = new Block("block two");
block1.method();
block2.method();
Hope it helps.
CodePudding user response:
A class in javascript is a function sprinkled with syntactic sugar. (reason: in javascript 'prototypal inheritance instead of the "regular" class-based inheritance as in e.g. python, java).
A function in javascript is a first-class citizen, so a function can be both the input, as well as the output of another function.
This leads to the following deductions/conclusions:
A function can output another function.
A function can output a class.
A class can output another class.
I hope this will help.