简体   繁体   English

节点JS类实例化的预期行为

[英]Node JS class instantiation expected behavior

I am curious to know that when you create a class as follows, does this class become a new instance for every file import. 我很好奇,当您按如下方式创建一个类时,该类是否会成为每个文件导入的新实例。

class _Http {

}

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

Is this class newed up every time I require or import the file. 每次我需要或导入文件时,是否会更新此类。 For example: 例如:

If I import the file into view/splash.js and then into view/groups.js as follows: 如果我将文件导入到view / splash.js中,然后再导入到view / groups.js中,如下所示:

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

Is this the same instance? 这是同一实例吗? I have read that this is a singleton pattern but it seem like the import would new up the instance. 我已经读到这是一个单例模式,但似乎导入会更新实例。

Is this class newed up every time I require or import the file. 每次我需要或导入文件时,是否会更新此类。

No. What you've exported is the variable Http . 否。您导出的是变量 Http Your initialization of that variable happens only once (given your code). 该变量的初始化仅发生一次(根据您的代码)。

If I import the file into view/splash.js and then into view/groups.js as follows: 如果我将文件导入到view/splash.js ,然后再导入到view/groups.js ,如下所示:

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

Is this the same instance? 这是同一实例吗?

Yes. 是。 It's the same variable (technically, a live binding to the variable), which can only contain one thing (in this case, a reference to the instance you created). 它是同一变量(从技术上讲,是对该变量的实时绑定 ),只能包含一件事(在这种情况下,是对您创建的实例的引用)。

In fact, if your code in the module defining it changed the value at some point, that change would be visible in all of the modules using it. 实际上,如果您在定义它的模块中的代码在某个时候更改了该值,则该更改将在使用它的所有模块中可见。 You're genuinely exporting a live link to the variable, not a copy of its value. 您实际上是在导出到变量的实时链接,而不是其值的副本。 (These semantics may not be perfectly preserved by things that take ES2015 module syntax and turn it into something else, but that's how it's defined to work.) (采用ES2015模块语法并将其转换为其他语法的东西可能无法完全保留这些语义,但这就是它的定义工作方式。)

For instance, if you had this: 例如,如果您有:

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

and then used it like this: 然后像这样使用它:

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

in this page: 在此页面中:

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

on a browser like the current Chrome which has native support for ES2015+ modules, you'd see that script.js sees the changes mode.js makes to a in its theVar binding. 像这对ES2015 +模块的原生支持目前的Chrome浏览器,你会看到script.js看到变化mode.js使得以a在其theVar结合。 Live example (again, requires a cutting-edge browser with modules support) . 实时示例 (同样,需要具有模块支持的最新浏览器)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM