是否可以为所需文件获得其他范围? [英] Is it possible to get a different scope for a required file?

查看:70
本文介绍了是否可以为所需文件获得其他范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个示例文件import.js

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(){
   console.log(self.a, self.b)
}
module.exports = Test






当我需要文件并创建一个新的对象时'一切正常,但是当我创建第二个对象时,它们都可以访问自我,只有后者可以工作。


When I require the file and create one new 'object' everything works perfectly, but when I create a 2nd object, they both have access to self, only the latter one works.

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

var one = new Test(1,2);
one.run()
1 2

var two = new Test(3,4);
two.run()
3 4
one.run()
3 4

有没有一种方法可以重新请求文件,使其创建单独的作用域?

Is there a way to re-require the file such that it creates separate scopes?

将其放入两个不同的变量不会工作,

Putting it as two different variables doesn't work,

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

但是复制文件确实可以我在寻找什么。

But duplicating the file does exactly what I am looking for..

var Test1 = require('./import1');
var Test2 = require('./import2');
var one = new Test1(1,2);
var two = new Test2(3,4);
one.run();
1 2

是重写自己 this 可以,但是,但这是否可能不修改import.js文件或复制它?

Yes re-writing self into this would work but, But is this possible without modifying the import.js file, or duplicating it?

推荐答案

在这里回答我自己的问题,但是至少有两种方法可以实现...。

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

(1)删除缓存

如何在 require后删除模块在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)使用作用域

因为require会读取文件,然后运行

Because require reads the file and then runs it,

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

等价于

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

因此,如果不使用require而是读取文件,则可以在函数内部建立新作用域:

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); })(); 

文件内部的self现在将存储在您创建的函数范围内。所以再次:

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.

这篇关于是否可以为所需文件获得其他范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆