在导入后,JavaScript 类上的静态方法变为未定义。

huangapple go评论66阅读模式
英文:

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(&#39;Test.init&#39;);
  }
}
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(&#39;./test.cjs&#39;);
console.log(x.init) // &lt;- 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 &quot;module-name&quot;;
import { default as alias } from &quot;module-name&quot;;

huangapple
  • 本文由 发表于 2023年6月29日 12:22:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578030.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定