javascript access chain with nested object literals

巧了我就是萌 提交于 2019-12-25 07:04:22

问题


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

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?

Edit: 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?


回答1:


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


来源:https://stackoverflow.com/questions/19994179/javascript-access-chain-with-nested-object-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!