Is it possible to get a different scope for a required file?

后端 未结 2 929
[愿得一人]
[愿得一人] 2021-01-16 01:56

Assume I have this example file called import.js

var self;
function Test(a,b){
   this.a = a;
   this.b = b;
   self = this;
}
Test.prototype.run = function(         


        
2条回答
  •  佛祖请我去吃肉
    2021-01-16 02:40

    Answering my own question here, but there are at least two ways this is possible....

    (1) Deleting Cache

    How to remove module after "require" in node.js?

    var Test1 = require('./import.js');
    delete require.cache[require.resolve('./import.js')]
    var Test2 = require('./import.js');
    
    var one = new Test1(1,2);
    var two = new Test2(3,4);
    
    one.run()
    1 2
    two.run()
    3 4
    

    Doesn't even look that messy, although it's grossly inefficient and would get costly very fast to write code this way...


    (2) Using function Scope

    Because require reads the file and then runs it,

    var Test = require('./test.js');
    

    is equivelent to

    var Test = eval( fs.readFileSync('./test.js', 'utf8') );
    

    So, if instead of using require, you read the file you can establish new scopes inside of functions:

    var fs = require('fs');
    var File = fs.readFileSync('./import.js', 'utf8');
    var Test1, Test2;
    (function(){ Test1 = eval(File); })();
    (function(){ Test2 = eval(File); })(); 
    

    The self inside the file would now be stored inside the function scope you created. so once again:

    var one = new Test1(1,2);
    var two = new Test2(3,4);
    
    one.run()
    1 2
    two.run()
    3 4
    

    Slightly messier, but far faster then deleting the cache and re-reading the file every time.

提交回复
热议问题