Reputation: 401
If I define some class:
class MyClass {
static myVar = { someKey: someVal };
...
}
but instead of defining the static variable from within the class, I want to import it from another file:
// utils.js
export const someObject = { someKey: someVal };
...
Will this work?:
import { someObject } from './utils.js';
class MyClass {
static myVar = someObject;
...
}
edit: The title to this question would more accurately be: "Can I define an ES6 static field from an imported object?" Static fields are currently a stage-2 proposal for JS. See @T.J.Crowder's answer below. and require the "babel-preset-stage-2" transpiler.
Upvotes: 0
Views: 286
Reputation: 1074048
That's not a static method, it's a static field (which isn't standard yet; static fields are currently at Stage 2, although it's common to transpile the syntax as the basics of it seem unlikely to change).
But provided the semantics when static fields are standardized are as they currently stand (and it would be weird if they weren't), yes, you can do that. The initializer of a field can be any expression, including one that uses an imported binding.
If you want to do it now, without transpiling or waiting for static fields to become standard, just do the assignment afterward:
import { someObject } from './utils.js';
class MyClass {
// ...
}
MyClass.myVar = someObject;
Upvotes: 3