简体   繁体   中英

Adding a Property to the Top-level Object in a Node Module

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM