javascript - 为什么我不能在 Node.js 中从另一个文件中设置一个导出变量?

标签 javascript node.js

考虑这两个程序:

testing1.js:

'use strict';
var two=require('./testing2');

two.show();
two.animal='Dog';
two.show();

testing2.js:

'use strict';
var animal='Cat';

function show()
   {
   console.log(animal);
   }

module.exports.animal=animal;
module.exports.show=show;

当我在 Node.js 中运行它时,它会打印“Cat Cat”。我希望它打印“猫狗”。为什么打印“Cat Cat”,如何让它打印“Cat Dog”?

最佳答案

我认为这里的问题是 two.animalvar animal 是两个不同的变量。 show 函数始终记录在 testing2.js

中定义的 var animal

对于 testing2.js 我会做这样的事情:

'use strict';

module.exports = {
    animal: 'Cat',
    show: function () {
        console.log(this.animal); // note "this.animal"
    }
}

然后在testing1.js中:

'use strict';

var two = require('./testing2.js');

two.show(); // => Cat
two.animal = 'Dog'; // now replaces 'Cat'
two.show(); // => Dog

关于javascript - 为什么我不能在 Node.js 中从另一个文件中设置一个导出变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38728296/

相关文章:

javascript - jQuery - 从输入值计算日期,六个月

javascript - 试图理解这个函数定义的行为

node.js - Jest 模拟子模块功能

javascript - 如果填充了特定值,则通过电子邮件发送电子表格中的数据

javascript - 使用 JS 对图像进行切片和混杂

javascript - HTML 在下面的标签中显示输入结果

javascript - Node.JS/Passport/Sequelize - 使用错误密码登录

javascript - 在javascript中的for循环中维护http请求的顺序

node.js - 如何监听NodeJS https套接字关闭事件

javascript - node js Express 连接mysql