Re: Multifile extensions with global variables that are not constant



2012/5/14 Amy C <mathematical coffee gmail com>:
> I'm writing an extension with multiple .js files, but where some need
> access to variables in others. These variables are not constant.
>
> As an example, in the main `extension.js`, imagine the following occurs:
>
> // load the other .js files, theme.js & toon.js
> const Theme = Extension.theme;
> const Toon = Extension.toon;
>
> var theme = new Theme.Theme();
> var toons = [];
> for ( let i=0; i<10; ++i ) {
>    toons.append( new Toon.Toon() );
> }
>
> In my situation, the Toon.Toon class needs access to the 'theme'
> variable to get some information from it.
> However if I just use 'theme.[property]' from within toon.js without
> declaring theme first, this is a syntax error (understandably).

It should be a ReferenceError, not a SyntaxError (but I see a spurious
dot there)

> Is the only way to give the `Toon.Toon` class access to `theme` to
> provide it in the initialiser?:
>    toons.append( new Toon.Toon(theme) );
>
> Or is it possible to put in the toon.js file something like
>    const GLOBAL = (????); // any variables that are shared between
> files live here
> and then have `theme.js` populate `GLOBAL.theme` with a pointer to the
> `theme` object, and have `toon.js` access (the updated!)
> `GLOBAL.theme`?

Even better, you can access variables directly from the module.
So in toon.js you would declare "const Theme = Extension.theme", and
then use Theme.theme (or Theme.toons, or anything else declared as a
variable within theme.js). All of let, const and var declarations
should work.
(Personally, I would still use a parameter to the constructor, as I
looks cleaner, but that's a matter of taste)

Giovanni


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]