gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:02:57 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com