[Knowledge Points] Some understandings of require in JavaScript

The following content is based on personal understanding. If there are any errors, please point them out.

guess

        When the same file is required in multiple files, for the first request, the file will be read and executed, and then added to the cache; when the file is required again later, it will only point to this cache, which can be understood as setting a A pointer to this cache, but the file will not be executed again.

        Due to the existence of cache, requiring the same file in multiple places actually controls the same cache. Therefore, modifications in one place will affect another place, which can be understood as global.

verify

main.js:

var test1 = require('./test1');
var test2 = require('./test2');

test1.js

var test3 = require('./test3');

log('t1');
test3.t3("1");

var myapp = {}

function t1 () {
    log('t1');
}

myapp.t1 = t1;
module.exports = myapp;

test2.js

var test3 = require('./test3');

log('t2');
test3.t3("2");
var myapp = {}

myapp.t2 = function t2 () {
    log('t2');
}

module.exports = myapp;

test3.js

var myapp = {}

log('t3');

var tt = "0"
myapp.t3 = function t3 (a) {
    log(tt);
    log(a);
    tt = a;
}

module.exports = myapp;

operation result

Result analysis

       1. t3, t1, 0: It means that var test1 = require('./test1'); in main.js calls test1.js, where var test3 = require('./test3'); in test1.js; Test3.js is called again, so t3 is output first, and then test1.js continues to execute, and t1 is output;

        2. 0, 1: Immediately afterwards, test3.t3("1"); in test1.js called the method in test3, first outputting the value of the global variable tt as 0, and then outputting the modified value as 1;

        3. t2: Go back to main.js and continue execution. At var test2 = require('./test2'); test2.js is called. In fact, the first line of test2.js is var test3 = require('. /test3'); called test3.js. According to the description in point 1, if the test3.js file is read and executed, t3 should be output, but it is not here, which means that test3.js is not executed;

        4, 1, 2: Immediately afterwards, test3.t3("2") was also executed in test2.js; the method in test3 was called, and the value of the global variable tt was first output as 1, which shows that the value modified in step 2 The value is retained, and the modified value is output as 2;

        Summary: In summary, the initial conjecture has been demonstrated.

Guess you like

Origin blog.csdn.net/sxf1061700625/article/details/133422269