【问题标题】:which memory is using node module to save data?and how compiler know about it?how node module work?哪个内存正在使用节点模块来保存数据?编译器如何知道它?节点模块如何工作?
【发布时间】:2015-09-29 08:33:31
【问题描述】:

我在 node.js 和堆栈溢出方面也非常大。我正在阅读节点模块并且无法理解一些东西,比如我创建了一个节点模块,

math.js

var a = 10;    
module.exports = {    
    add: function (num) {    
        a += num;    
        return a;    
    }    
} 

然后我将这个 math.js 导出到以下两个文件中

a.js

var math = require("./math.js");
var q = math.add(10);
console.log(q);

b.js

var math = require("./math.js");
var q = math.add(10);
console.log(q);

都给我 ans 20 和 20

但是当我在另一个 main.js 文件中包含这个 a.js 和 b.js 时

main.js

var a= require("./a.js");
var b= require("./b.js");

它为我提供了 ans 20 & 30 。那么为什么它不提供 20 和 20 呢?它使用哪个内存来保存模块数据?谁能解释一下吗?

【问题讨论】:

    标签: node.js math


    【解决方案1】:

    NodeJS 中的模块处于“单例”模式。每个模块只创建一次,当您第二次调用require 时,您将获得前一个对象。

    用你的例子做一点解释:

    a.js

    // Math is created
    var math = require("./math.js");
    
    // 10 is added to the interval variable a of math.js. so q is 20
    var q = math.add(10);
    console.log(q);
    

    b.js

    // Math is created
    var math = require("./math.js");
    
    // 10 is added to the interval variable a of math.js. so q is 20
    var q = math.add(10);
    console.log(q);
    

    现在是棘手的:

    main.js

    请允许我“重写”main.js 的代码,我只是将每个require 替换为他们自己的代码

    // ********************************************
    // require('./a.js);
    // Math is created, so the internal variable a is 10
    var math = require("./math.js");
    
    // 10 is added to the interval variable a of math.js. so q is 20
    var q = math.add(10);
    console.log(q);
    
    // ********************************************
    // require('./b.js);
    // Math is not re-created here. NodeJS will re-use the previous result of require("./math.js");. So the internal variable a is still 20 here
    var math = require("./math.js");
    
    // 10 is added to the interval variable a of math.js. so q is 30
    var q = math.add(10);
    console.log(q);
    

    你想变得更狡猾吗?只需这样做:

    require('./a.js');
    require('./a.js');
    require('./a.js');
    require('./a.js');
    require('./a.js');
    require('./a.js');
    

    此代码将只打印 20,只打印一次。因为模块a 只会在第一次调用时创建。它每次都返回undefined(因为你在a.js中没有module.exports=...),但只有第一次会执行它的代码。

    【讨论】:

    • 谢谢你。魔术师,但我无法理解在执行我的 main.js 程序时,“a”的值将保存在哪里以便我得到 30?意味着它在哪些内存上保存了“a”的值?跨度>
    • 变量a在模块math.js的“内存”中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2016-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多