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

后端 未结 2 911
[愿得一人]
[愿得一人] 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:32

    In short, it is not possible to do this without modifying import.js file or duplicating the file. This is because self is a global variable for that document, which will be the same for every instance of the function object.

    Alternative #1

    The problem is that you assign self to a global variable. Both of these have access to the same variable and therefore you get the observed results. Also, your use of self is unneccessary. The code below works as you described.

    function Test(a,b){
       this.a = a;
       this.b = b;
    }
    Test.prototype.run = function(){
       // Simply using 'this' to access the properties of the function is sufficient - no need for self
       console.log(this.a, this.b)
    }
    module.exports = Test
    

    Working example

    In this case with each new Test() instance you will have a separate instance, so you will not need to 're-require' the files.

    Alternative #2

    If you want to keep self as per your edit, another option would be to just rewrite the function you want to call. For example:

    var Test = require('./import.js');
    
    Test.prototype.run = function(){
       console.log(this.a, this.b)
    }
    

    If this is also not an option, then you need to provide more information as to what you can or cannot do.

提交回复
热议问题