How does Node.js assign values to the outermost variables in a function? When the parameter name is the same as the variable name

pay attention to the environment. This is a piece of Node.js back-end code, not the js code in html.
the assignment function has the same parameter as the variable name. How to assign the value without changing the parameter name?

// test.js
var x;// x

init(12)// x
console.log(`x:${x}`);// 

// ,?
function init(x){
    // nodejs,window.x=x
    x = x;
}

there is another question: is the variable x in this code a global variable or a local variable?
if it is the js code in html, x is undoubtedly a global variable belonging to the window object.
but if it is in the back-end environment of Node.js, the global object is the global, user code, not in the outermost layer, only those defined in this.x or var global.x are global variables.

my guess is:
the js file is a module in Node.js, then x should be a local variable belonging to the module, and the local variable defined in the internal function belongs to the subordinate relationship of the scope chain.
global object scope-> module object scope-> function object scope
but why do you use this in the module to point to global?

Dec.17,2021

global

global in node is the host of global variables. All you need here is global.x
.
the assignment function has the same parameter as the variable name. How to assign the value without changing the parameter name?

No way. You need to know what a scope is. Of course, if window.x/global.x or other .x I don't think it's a problem.

about your conjecture

(function(exports, require, module, __filename, __dirname) {
    // 
});

this is not entirely about nodejs , but about module . You can try it with the nodejs command line, which is very similar to browser .

Menu