全局变量替代 [英] Global Variables alternative

查看:258
本文介绍了全局变量替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个可供所有.js文件访问的数组。这个数组也必须是可更新的,并且更新后的更改必须反映在使用该数组的所有其他文件中。



我读过使用GLOBAL变量不是好的方法,但有什么替代方法?

  //文件1包含我的全局变量
var mySharedArray = [' HELO'];
module.exports = {
mySharedArray:mySharedArray,
get:function(){
console.log(mySharedArray);



//文件2我在推新数据
router.get('/ workerequestest',function(req,res){
queue.push(moreData);
require('../ config / globalQueue')。get();
require('../ config / startWorkerQueue');
res.send(200,'message received');
});

//文件3其中我正在检查更新的值
var interval = setInterval(function(){
var Queue = require('../ config / globalQueue') .mySharedArray;
require('../ config / globalQueue').get();
},10000,'hello','检查新进程');


解决方案

node.js中的适当模块化不使用实际的全局变量因为这使得真正利用可复用模块更加复杂,并可能与其他全局变量产生冲突。



可以使用的一种设计模式是将共享数据置于它自己的模块,然后在该模块中只需要 require()

  //共享数据.js 
var mySharedArray = [...];

module.exports = {
mySharedArray:mySharedArray
}


$ b $然后,在每个想要访问该数组的模块中,可以这样做:

  // someothermodule .js 

var sharedArray = require('./ shared-data.js')。mySharedArray;


//这个修改会改变主数组,并且会被
看到//所有共享它的模块
sharedArray.push(moreData) ;

这是因为在Javascript中分配数组时,它们不会被复制,而是指向原始数组是共享的。因此,对赋值的任何修改都只是指向原始对象,并因此更改了原始数组。因此,所有模块都可以访问相同的原始数组。






我刚刚在我自己的三个文件中测试了这个概念,它工作正常。以下是我的三个文件:

服务器文件

  // shared-server.js 
var express = require('express');
var app = express();
var server = app.listen(80);
var shared = require('./ shared-var');
require('./ shared-interval.js')

var cntr = 0;

app.use(express.static('public'));
$ b $ app.get(/ test,function(req,res){
shared.mySharedArray.push(++ cntr);
shared.get();
res.send(200,'message received');
});

共享变量文件:

  //共享var.js 
var mySharedArray = ['helo'];
module.exports = {
mySharedArray:mySharedArray,
get:function(){
console.log(mySharedArray);


间隔档案

  // shared-interval.js 
var interval = setInterval(function(){
require(' ./shared-var')。get();
},1000);

当我运行它时,它输出 mySharedArray 每秒。每次我使用浏览器访问 http:// localhost / test 时,它会为 mySharedArray ,我可以在控制台中看到它。这是我期望的行为。


I want to create an array that is accessible to all the .js files. This array must also be updateable, and the updated changes must be reflected in all the other files using that array.

I have read that using a GLOBAL variable is not a good method, but what is the alternative?

//file 1 which contains my global variable
var mySharedArray = ['helo']; 
module.exports = {
mySharedArray: mySharedArray,
get: function(){
    console.log(mySharedArray);
} 
}    

//file 2 where i am pushing new-data 
router.get('/workerequestest',function(req,res){
queue.push("moreData");
require('../config/globalQueue').get();
require('../config/startWorkerQueue');
res.send(200,'message recieved');
});

//file 3 where i am checking the updated values
var interval = setInterval(function() {
var Queue = require('../config/globalQueue').mySharedArray;
require('../config/globalQueue').get();
}, 10000,'hello' ,'checking for New processes');

解决方案

Proper modularity in node.js does not use actual globals as that makes actually taking advantage of reusable modules more complicated and makes for possible conflicts with other globals.

One design pattern that can be used instead is to put the shared data in its own module and then just require() in that module wherever needed.

// shared-data.js
var mySharedArray = [...];

module.exports = {
    mySharedArray: mySharedArray
}

Then, in each module that wants to have access to that array, you can do this:

// someothermodule.js

var sharedArray = require('./shared-data.js').mySharedArray;


// this modification will change the main array and will be seen by
// all modules that are sharing it
sharedArray.push("moreData");

This works because when arrays are assigned in Javascript, they are not copied, but instead a pointer to the original array is shared. So, any modifications to the assigned value is just pointing at the original object and thus changes the original array. Thus, all modules would have access to the same original array.


I just tested this concept in my own three files and it works fine. Here are my three files:

Server File:

// shared-server.js
var express = require('express');
var app = express();
var server = app.listen(80);
var shared = require('./shared-var');
require('./shared-interval.js')

var cntr = 0;

app.use(express.static('public'));

app.get("/test", function(req, res) {
    shared.mySharedArray.push(++cntr);
    shared.get();
    res.send(200,'message received');
});

Shared Variable File:

//shared-var.js
var mySharedArray = ['helo']; 
module.exports = {
    mySharedArray: mySharedArray,
    get: function(){
        console.log(mySharedArray);
    } 
}

Interval File:

//shared-interval.js
var interval = setInterval(function() {
    require('./shared-var').get();
}, 1000);

When I run this, it outputs the value of mySharedArray every second. Each time I go to http://localhost/test with my browser, it adds a new value to mySharedArray and I see that in the console. This is the behavior I would expect.

这篇关于全局变量替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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