带有嵌套对象字面量的 javascript 访问链 [英] javascript access chain with nested object literals

查看:56
本文介绍了带有嵌套对象字面量的 javascript 访问链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,在该项目中,我有一个根对象字面量,用于存储在其余部分中使用的常量和枚举等内容,以及用于分隔不同功能的嵌套对象字面量.像这样:

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
}

基本上我使用顶级对象文字作为命名空间,其他对象/函数分布在多个文件中.唯一的问题是 root 对象的属性不能被 root 的孩子访问,例如 root.display.renderer 中的 enum 或 root.engine.processer 中的 CONST.如果 root 是一个函数对象,这将很容易通过原型链完成,但我希望 root 对象是静态的,并且仅用作容器.

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. 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.

在 Javascript 中完成此结构的最佳方法是什么?我可以使用更好的结构来实现项目封装的相同目标吗?

What is the best way to accomplish this structure in Javascript? Is there a better structure I can use that accomplishes the same goal of project encapsulation?

抱歉,我没有正确提及继承.我知道可以直接访问 root 的属性(通过 root.whatever).我想知道是否有可能在 root 的孩子中隐含对 root 的引用;除非使用直接引用是 Javascript 的标准做法?

Sorry, I wasn't properly refering to inheritance. I know that root's properties can be accessed directly (via root.whatever). I want to know if it's possible to have that reference to root be implicit inside children of root; unless using the direct reference is standard practise for Javascript?

推荐答案

你的意思是这样??(var"不是必需的,但鼓励使用.)

you mean like this?? ("var" is not needed but it is encouraged.)

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

这篇关于带有嵌套对象字面量的 javascript 访问链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆