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;
[...]

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.