简体   繁体   English

Node.JS全局变量声明本地名称是否相同

[英]Node.JS global variable declaring when local is same name

I have this code: 我有以下代码:

let manager;
exports.setup = async manager => {
    this.manager = manager;
};

This is possible duplicate but every time I saw this, solution was to use window.manager = manager to set global variable from inside function. 这可能是重复的,但是每次我看到这个,解决方案都是使用window.manager = manager从函数内部设置全局变量。 How to do this in Node.JS where is no window ? 如何在没有window Node.JS中执行此操作? this.manager not working, because its seems this.manager !== manager (the global one) this.manager无法正常工作,因为它似乎this.manager !== manager (全局manager

Your function parameter hides the local variable in this case. 在这种情况下,您的函数参数将隐藏局部变量。

Consider the following 2 modules: 考虑以下两个模块:

lib.js lib.js

let manager = 2;
exports.setup = async manager => {
    this.manager = manager;
};

main.js main.js

var v = require("./lib.js");
v.setup(5);
console.log(v.manager);

This prints 5 because manager is the parameter you pass to the function. 由于manager是您传递给函数的参数,因此将打印5 If you want to obtain the value of the local manager ( 2 in this example) you need to change the name of the function parameter or remove it entirely. 如果要获取本地manager的值(在此示例中为2 ),则需要更改功能参数的名称或将其完全删除。

let manager = 2;
exports.setup = async input => {
    this.manager = manager;
};

or 要么

let manager = 2;
exports.setup = async () => {
    this.manager = manager;
};

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

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