简体   繁体   English

是否可以从导入的对象定义ES6静态方法?

[英]Can I define an ES6 static method from an imported object?

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?" 编辑:此问题的标题将更准确地是:“我可以从导入的对象定义ES6静态字段吗?” Static fields are currently a stage-2 proposal for JS. 静态字段目前是JS的第二阶段建议。 See @TJCrowder's answer below. 请参阅下面的@TJCrowder的答案。 and require the "babel-preset-stage-2" transpiler. 并需要“ babel-preset-stage-2”转译器。

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). 这不是一个静态方法,它是一个静态字段 (尚不标准; 静态字段目前处于第2阶段,尽管由于语法的基础似乎不太可能更改,所以很常见)。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM