开发者

Putting my variables under a namespace

开发者 https://www.devze.com 2023-03-18 09:20 出处:网络
How can I create an object containing my variables using the same variable names, or with other words, how can I put my variables under a namespace?

How can I create an object containing my variables using the same variable names, or with other words, how can I put my variables under a namespace?

var a = "variable";
var b = "variable";

var obj = {
    a : a
    b : b
}

Is there a shorter way of doing this than this?

EDIT:

Let me clarify - I already have the variables a and b declared somewhere. Eventually at one point I want to send them all over to another function for example, but I want all variables under one namespace - obj. So Instead of doing the tedious redeclaring every single variable using the same variable names and same variable values (the variable itself) I thought maybe there was a shorthand way: like

var obj = objectify(a, b);

I wondered if there was something similar already build into the javascript lib开发者_Python百科rary.


As you are actually not putting the variables in the object but only copying their content into properties with the same names, you don't need to create the variables at all:

var obj = {
  a: "variable",
  b: "variable"
};

Note the comma between the properties, which is needed, and the semicolon after the object declaration, which is recommended.

You can also create an empty object, and add properties to it afterwards (or any combination you like):

var obj = {};
obj.a = "variable";
obj.b = "variable";


var obj = {
  a: "variable",
  b: "variable"
};

I may be misunderstanding your request here


There are no namespaces in the current version of javascript, so the only way is to put these variables in an object, which is what you did. You can also create an object and assign variables to it, though it is not shorter:

var x = {};
x.foo = "foo";


var a = "variable";
var b = "variable";
var obj = {};
obj[a] = a;
obj[b] = b;

Sorry for layout, but WYSIWYG editor has not any tabs(


You can't usefully put existing variables into a namespace object.

In particular, if you have:

var a = 1;
var b = "test";
var c = { ... };  // some object

var NS = {
    a: a,
    b: b,
    c: c
};

Then changes to a or b will not affect NS.a or NS.b, and vice-versa, since the entries in the NS object are copies of the originals.

However changes to the content of c will affect NS.c (and vice versa), since c is a reference to an object.

However anything you do that subsequently changes the reference stored in NS.c will break that link.

0

精彩评论

暂无评论...
验证码 换一张
取 消