将我的变量放在命名空间下
如何使用相同的变量名称创建包含变量的对象,或者换句话说,如何将变量放在命名空间下?
var a = "variable";
var b = "variable";
var obj = {
a : a
b : b
}
还有比这更短的方法吗?
编辑:
让我澄清一下 - 我已经在某处声明了变量 a 和 b 。最终,在某一时刻,我想将它们全部发送到另一个函数,例如,但我希望所有变量都位于一个名称空间 - obj.因此,我没有使用相同的变量名和相同的变量值(变量本身)进行繁琐的重新声明每个变量,我想也许有一种简写方法:就像
var obj = objectify(a, b);
我想知道是否已经在 javascript 库中构建了类似的东西。
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 library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于您实际上没有将变量放入对象中,而只是将其内容复制到具有相同名称的属性中,因此您根本不需要创建变量:
请注意属性之间的逗号(这是必需的)以及后面的分号对象声明,推荐使用。
您还可以创建一个空对象,然后向其添加属性(或您喜欢的任何组合):
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:
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):
我可能误解了你的要求
I may be misunderstanding your request here
当前版本的 javascript 中没有命名空间,因此唯一的方法是将这些变量放入一个对象中,这就是您所做的。您还可以创建一个对象并为其分配变量,尽管它并不短:
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:
抱歉布局,但所见即所得编辑器没有任何选项卡(
Sorry for layout, but WYSIWYG editor has not any tabs(
您无法将现有变量有效地放入命名空间对象中。
特别是,如果您有:
那么对
a
或b
的更改不会影响NS.a
或NS.b
>,反之亦然,因为NS
对象中的条目是原始条目的副本。然而,对
c
的内容的更改将会影响NS.c
(反之亦然),因为c
是一个对对象的引用。但是,您随后所做的任何更改存储在
NS.c
中的引用都会破坏该链接。You can't usefully put existing variables into a namespace object.
In particular, if you have:
Then changes to
a
orb
will not affectNS.a
orNS.b
, and vice-versa, since the entries in theNS
object are copies of the originals.However changes to the content of
c
will affectNS.c
(and vice versa), sincec
is a reference to an object.However anything you do that subsequently changes the reference stored in
NS.c
will break that link.