javascript access chain with nested object literal

2019-08-29 04:29发布

问题:

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