Is this idea or a similar one possible in es6?
function() {
class A {}
}
Yes, because a class is just Syntactic Sugar for a function that cannot be called. Instead, it must be instantiated with new. You can play around with https://babeljs.io/repl/ to see what a class actually looks like.
Example
/* ES6 code */
class Car {
constructor() {
this.wheels = 4;
}
}
/* generated ES5 code */
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Car = function Car() {
_classCallCheck(this, Car);
this.wheels = 4;
};
Yes, this does work exactly as you've written (sans the missing function name).
However, I would advise against it. Dynamically creating classes in functions that are called multiple times defeats the purpose of sharing methods (etc), as every invocation would create a new prototype. Never do this when you actually only need to create a custom instance in that function.
If you are using ES6 modules, just put the class declaration outside of your function but don't export it. If you aren't using modules, just wrap both the class and the function in an IIFE.
An exception to above rule is when you really need to dynamically create a few classes. As they would be looking quite similar, they're probably subclasses of some common ancestor though.
class Common {
…
}
function makeSubclass(…) {
return class Sub extends Common {
…
};
}
const Sub1 = makeSubclass(…);
const Sub2 = makeSubclass(…);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With