[英]javascript access chain with nested object literals
I'm working on a project where I have a root object literal that stores things like constants and enums used throughout the rest of it, and nested object literals to separate different functionality. 我正在一个项目中,我有一个根对象文字,它存储在整个其余部分中使用的常量和枚举之类的东西,以及嵌套的对象文字以分隔不同的功能。 Something like this: 像这样:
root = {
enum : {
FIRSTVAL : 0,
SECONDVAL : 1,
THIRDVAL : 2,
},
CONST : 0xFFE8,
}
root.display = {
renderer : function() {
// do something...
do_some_fun(enum.FIRSTVAL);
}
// other functions
}
root.engine = {
processor = function() {
// do some stuff
run_calculations(CONST);
}
// some other functions
}
Basically I'm using the top-level object literal as a namespace, with the other objects/functions spread out in multiple files. 基本上,我将顶级对象文字用作命名空间,其他对象/功能分散在多个文件中。 The only problem is that the properties of the root object aren't accessible by root's children, such as enum in root.display.renderer or CONST in root.engine.processer. 唯一的问题是,根对象的子对象无法访问根对象的属性,例如root.display.renderer中的enum或root.engine.processer中的CONST。 If root was a function object this would be simple to accomplish through the prototype chain, but I want the root object to be static and merely serve as a container. 如果root是函数对象,那么通过原型链可以很容易地实现,但是我希望root对象是静态的,并且仅用作容器。
What is the best way to accomplish this structure in Javascript? 在Java中完成此结构的最佳方法是什么? Is there a better structure I can use that accomplishes the same goal of project encapsulation? 我是否可以使用更好的结构来实现项目封装的相同目标?
Edit: Sorry, I wasn't properly refering to inheritance. 编辑:对不起,我没有正确地指代继承。 I know that root's properties can be accessed directly (via root.whatever). 我知道可以直接(通过root.whatever)访问root的属性。 I want to know if it's possible to have that reference to root be implicit inside children of root; 我想知道是否有可能在root的子代中隐含对root的引用; unless using the direct reference is standard practise for Javascript? 除非使用直接参考是Javascript的标准做法?
you mean like this?? 你的意思是这样吗? ("var" is not needed but it is encouraged.) (不需要“ var”,但建议使用。)
var root = {
enum : {
FIRSTVAL : 0,
SECONDVAL : 1,
THIRDVAL : 2,
},
CONST : 0xFFE8,
}
root.display = {
renderer : function() {
console.log(root.enum.FIRSTVAL);
}
}
root.engine = {
processor : function() {
console.log(root.CONST);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.