在动态加载一个模块后,即在解析了相应的promise 后,可以对结果使用函数或lambda表达式.我惊讶地发现模块实例(由promise提供)没有原型:

import("./module.js").then(x => {
    console.log(typeof x); // yields 'object' as expected
    console.log(x instanceof Object); // yields false !!
    console.log(x.__proto__); // yields undefined !!
    console.log(Object.getPrototypeOf(x)); // yields null !!

    // but one can certainly access exported variables / functions
    x.exportedFunction();
})

显然,尽管x是一个"对象",但它似乎不是Object实例,而且似乎根本没有任何原型.我甚至不知道这是可能的.Firefox/Chrome和Safari都给出了相同的输出(我在代码注释中详细说明的输出).有什么解释吗?这是在什么地方指定的吗?这个模块x是什么样的对象?

Note:我不熟悉Typescript ,所以我不确定我的问题是否可以被认为是this one的重复

Edit:我刚刚意识到,对于静态导入到名称空间中的模块或通过import * as x from "./module.js"获得的module object,可以获得相同的奇怪伪对象.虽然MDN提到了这些对象,但没有详细说明它们是什么.

推荐答案

有一个所谓的100的整个范围,它偏离了101.导入的ES6模块实例的类型如下:

如果对象的[[GetPrototypeOf]、[[SetPrototypeOf]、[[IsExtensible]、[[PreventExtensions]、[[GetOwnProperty]、[[DefineOwnProperty]、[[HasProperty]、[[Get]、[[Set]、[[Delete]]和[[OwnPropertyKeys]内部方法使用本节中的定义,并且其其他基本内部方法使用10.1中的定义,那么对象就是module namespace exotic object.这些方法由ModuleNamespaceCreate安装.

为什么x 100 Objectx.101Object.102(x)的行为如此怪异?让我们看看这里涉及的对象的内部方法:

GetPrototypeOf

模块名称空间的[[GetPrototypeOf]]内部方法

1. Return null.

这些物体是如何产生的?这里有special method个:

ModuleNamespaceCreate ( module, exports )

抽象操作ModuleNamespaceCreate接受参数模块(a

1. Assert: module.[[Namespace]] is empty.
2. Let internalSlotsList be the internal slots listed in Table 35.
3. Let M be MakeBasicObject(internalSlotsList).
4. Set M's essential internal methods to the definitions specified in 10.4.6.
5. Set M.[[Module]] to module.
6. Let sortedExports be a List whose elements are the elements of exports ordered as if an Array of the same values had been sorted using %Array.prototype.sort% using undefined as comparefn.
7. Set M.[[Exports]] to sortedExports.
8. Create own properties of M corresponding to the definitions in 28.3.
9. Set module.[[Namespace]] to M.
10. Return M.

Javascript相关问答推荐

Klaro与Angular的集成

useNavigation更改URL,但不呈现或显示组件

我不知道为什么setwritten包装promise 不能像我预期的那样工作

仅针对RTK查询中的未经授权的错误取消maxRetries

用JavaScript复制C#CRC 32生成器

在运行时使用Next JS App Router在服务器组件中运行自定义函数

Eval vs函数()返回语义

如何将未排序的元素追加到数组的末尾?

如何使用JS创建一个明暗功能按钮?

MarkLogic-earch.suggest不返回任何值

每次重新呈现时调用useState initialValue函数

将基元传递给THEN处理程序

匹配一个或多个可选重复的特定模式

无法重定向到Next.js中的动态URL

在Vercel中部署Next.js项目时获取`ReferenceError:未定义文档`

为列表中的项目设置动画

如果NetSuite中为空,则限制筛选

MongoDB通过数字或字符串过滤列表

在没有任何悬停或其他触发的情况下连续交换图像

将字体样式应用于material -UI条形图图例