javascript - Node JS 类实例化预期行为

标签 javascript node.js ecmascript-6

我很好奇,当您按如下方式创建一个类时,该类是否会成为每次文件导入的新实例。

class _Http {

}

let Http = new _Http();
export default Http;

每次我需要或导入文件时,这个类都会更新吗?例如:

如果我将文件导入 view/splash.js,然后导入 view/groups.js,如下所示:

从'../../utils/http'导入http;

这是同一个实例吗?我读到这是一个单例模式,但似乎导入会更新实例。

最佳答案

Is this class newed up every time I require or import the file.

没有。您导出的是变量 Http。该变量的初始化仅发生一次(给定您的代码)。

If I import the file into view/splash.js and then into view/groups.js as follows:

import http from '../../utils/http';

Is this the same instance?

是的。它是同一个变量(从技术上讲,是到变量的实时绑定(bind)),但只能包含一个内容(在本例中是对您创建的实例的引用)。

事实上,如果定义它的模块中的代码在某个时刻更改了该值,则该更改将在使用它的所有模块中可见。您真正导出的是变量的实时链接,而不是其值的副本。 (采用 ES2015 模块语法并将其转换为其他内容的事物可能无法完美保留这些语义,但这就是它的定义方式。)

例如,如果您有这个:

export let a = 0;
setInterval(() => { // For demonstration purposes only
    ++a;
}, 500);

然后像这样使用它:

import { a as theVar } from './mod.js';
const display = document.getElementById("display");
setInterval(() => {
    display.innerHTML = String(theVar);
}, 50);

在此页面中:

<body>
  <p id="display"></p>
  <script type="module" src="script.js"></script>
</body>

在像当前 Chrome 这样原生支持 ES2015+ 模块的浏览器上,您会看到 script.js 看到 mode.js 在其 theVar 绑定(bind)中对 a 所做的更改。 Live example (同样,需要具有模块支持的尖端浏览器)

关于javascript - Node JS 类实例化预期行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694900/

相关文章:

javascript - 动态添加字段的 jQuery 表单验证

javascript - D3 CSV到JSON邻接列表,如何访问节点颜色?

node.js - 谷歌 API 网关 + Firebase : X-Apigateway-Api-Userinfo vs X-Forwarded-Authorization headers

import - 带有 Babel 延迟加载模块的 Webpack 使用 ES6 推荐的 Import() 方法不起作用

javascript - Angular指令回调函数

javascript - Protractor 计数()期望意外失败

node.js - 如何增加nodejs默认内存?

javascript - 表示没有设置Cookie

javascript - 如何在 JavaScript 中有选择地定义/声明对象的键?

javascript - ES6 Promise.all() 错误句柄 - 是否需要 .settle()?