I believe this is technically by design (see discussion on expression vs. declaration for classes here), but I cannot find a way to get global class declarations to work as expected using eval
, though there are no issues with global function declarations. This is actually the first time I've seen eval(...)
produce a different system state than just embedding the code directly into the file.
For example:
// SHOULD declare global window.GlobalTest
class GlobalTest {}
// no problem!
console.log({ GlobalTest });
// SHOULD declare window.A, and window.B
eval('function A(){} function B(){}');
// no problem!
console.log({ A, B });
// SHOULD declare window.EvalTest
eval('class EvalTest {};');
// uh-oh! EvalTest is undefined =(
console.log(`typeof EvalTest: ${typeof EvalTest}`);
/* THINGS THAT WORK */
// single expression + assignment (boo!)
let SingleExpression = eval('(class SingleExpression {})');
console.log({ SingleExpression });
// assignment (boo!)
eval('AssignmentExpression = class {}');
console.log({ AssignmentExpression });
Running eval
in the global scope, we can declare multiple top-level functions without issue. Classes, however, work differently - it only seems possible to declare a global class using eval
by assigning it (i.e., EvalTest = class {}
), but this requires processing the code rather than it just... working.
The other approach is to isolate the class completely, wrapping it in parentheses to make it an expression, and then assigning the results of the eval(...)
call (see SingleExpression
in example). This seems strange, because in the global scope, we have no problem declaring a class with class GlobalTest {}
in any environment that I have tested. Yet inside eval
, it falls apart. In any case, this also requires preprocessing of the code.
I have a script that contains multiple classes and functions, and there seems to be no way to run it as expected and declare multiple global classes with one eval
call unless I preprocess the code just so that class MyGlobalClass {}
works as expected. Global function/object declarations are not an issue.
Am I missing something obvious here? Any advice would be appreciated. I know - "it's not a bug, it's a feature" - but it just seems weird that class declarations do not actually declare anything inside eval
, whereas every other variable declaration does. Embarrassingly enough, until I bumped into this issue, I thought classes were just syntactic sugar for functions, but it's clearly more complex than that.