英文:
Static method on JavaScript class becomes undefined after imported
问题
I have this simple JavaScript class with a static method:
// test.cjs
class Test {
static init() {
console.log('Test.init');
}
}
exports.default = Test;
exports.Test = Test;
Now if I import the Test class in another file like below:
// index.mjs
const { default: x } = await import('./test.cjs');
console.log(x.init) // <- this will be `undefined`
I'm confused here, how come x.init becoming undefined?
Here's a demo where you can test the code online https://stackblitz.com/edit/stackblitz-starters-4alfhc?file=test.cjs,index.mjs
英文:
I have this simple JavaScript class with a static method:
// test.cjs
class Test {
static init() {
console.log('Test.init');
}
}
exports.default = Test;
exports.Test = Test;
Now if I import the Test class in another file like below:
// index.mjs
const { default: x } = await import('./test.cjs');
console.log(x.init) // <- this will be `undefined`
I'm confused here, how come x.init becoming undefined?
Here's a demo where you can test the code online https://stackblitz.com/edit/stackblitz-starters-4alfhc?file=test.cjs,index.mjs
答案1
得分: 0
你不能访问名为 default 的属性(至少不能这样)。尝试这样做将返回 exports 的值,而不是 exports.default。这是有意设计的。 "default" 具有特殊的含义,用于返回主要(默认)导出值,并因此覆盖了标准行为。
import(...) 作为类似函数的动态方式,试图 "模拟" import 语句(静态声明)的行为。
请参阅MDN: import,以及MDN import() 以及如何不同对待 { export1 as alias1 } 与 { default as alias1 },即使在 StackOverflow 的高亮中也是如此:
import { export1 as alias1 } from "module-name";
import { default as alias } from "module-name";
英文:
You cannot access a property called default (at least not like that). Trying that will return the value of exports instead of exports.default. That's by design. "default" has the special meaning of returning the main(/default) export value and therefor overrides the standard behavior.
import(...) as a function-like dynamic tries to "emulate" the behavior of the import statement (static declaration).
See MDN: import as well as MDN import() and how { export1 as alias1 } is treated differently as { default as alias1 }, it's treated differently even in the highlight on StackOverflow:
import { export1 as alias1 } from "module-name";
import { default as alias } from "module-name";
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论