0

In a node.js module a variable declaration stays private inside the module:

var a = 'x';

Let's say, I want to declare a number of variables in this manner. I cannot use the following code, because like this the variables become really global and visible in other modules as well:

var xs = ['a', 'b', 'c', 'd'];
for (key in xs) {
  var value = xs[key];
  global[value] = 'x';
}

Is there a way to do this just for the module? I need this because I am requiring a library ('gl-matrix'), which itself has several sub-objects I need to access in the module easily. I want to avoid:

var gl_matrix = require('gl-matrix');
var vec2 = gl_matrix.vec2;
var vec3 = gl_matrix.vec3;
var mat3 = gl_matrix.mat3;
[...]
Anton Harald
  • 5,772
  • 4
  • 27
  • 61

1 Answers1

0

Not entirely sure why you want to declare variables that way. However if that's the approach you're taking, this should work...

var declareObjKeyVal = function(arr, val) {
  var obj = {};
  for (key in arr) {
    obj[arr[key]] = val;
  }
  return obj;
}

var xs = ['a', 'b', 'c', 'd'];
var xs_val = 'x';
var new_vars = declareVars(xs, xs_val);

If you're looking to make a complete copy of the gl_matrix object, you could do this...

var copyObj = function(obj) {
  var cobj = {};
  for (key in obj) {
    cobj[key] = obj[key];
  }
  return cobj;
}

var gl_matrix_copy = copyObj(gl_matrix);

Or if you're looking for a specific subset of values you can add a conditional...

var copyObjKeyVals = function(obj, keys) {
  var cobj = {};
  for (key in obj) {
    if(keys.indexOf(key) > -1){
      cobj[key] = obj[key];
    }
  }
  return cobj;
}

var gl_keys = ['vec2', 'vec3', 'mat3'];
var gl_matrix_copy = copyObjKeyVals(gl_matrix);
bk3
  • 21
  • 4
  • thanks for the propose. In your examples the variables are gathered within an object again. I try to have them immidiately in the global space of the module - but not in the node object 'global', which is available throughout the app. – Anton Harald Sep 15 '15 at 22:25