How do I give multiple JavaScript objects across multiple files access to same private variable?

前端 未结 3 1257
野的像风
野的像风 2020-12-07 03:50

If I want to span my JavaScript project across multiple source files, but have each file have access to the same private variable, how would one do that?

For example

相关标签:
3条回答
  • 2020-12-07 04:04

    The only way that you can share _secret is attaching it to the application object and then application object to the window object. Here is an example.

    // FIRST JS FILE...
    var application; // will be attached to window
    
    (function(app) {
      
      app.secret = "blah!"; // will be attached to application
      
    })(application || (application = {}));
    
    
    
    // ANOTHER JS FILE
    var application;
    
    (function(app) {
      
      app.method1 = function(){ console.log(app.secret); }; // will be attached to application;
      
    })(application || (application = {}));
      
    console.log(application.method1()); // will display 'blah!' on the console

    Working example on jsbin

    0 讨论(0)
  • 2020-12-07 04:06

    How do I put app.part01 and app.part02 in seperate files, but still have access to _secret?

    That's impossible indeed. Script files are executed in the global scope, and don't have any special privileges. All variables that they will be able to access are just as accessible to all other scripts.

    Copying and pasting everything inside a single function each time before testing is not something I want to do

    What you are looking for is an automated build script. You will be able to configure it so that it bundles your files together, and wraps them in an IEFE in whose scope they will be able to share their private state. The most simple example:

    #!/bin/sh
    echo "APP = (function () {
        var _secret = {},
            app = {};" > app.js
    cat app.part01.js >> app.js
    cat app.part02.js >> app.js
    echo "    return app;
    }());" >> app.js
    
    0 讨论(0)
  • 2020-12-07 04:14

    One way I was able to accomplish this was to create a JS file that contained the global object.

    // Define a global object to contain all environment and security variables
    
       var envGlobalObj = {
          appDatabase:      process.env.YCAPPDATABASEURL,
          sessionDatabase:  process.env.YCSESSIONDATABASEURL,
          secretPhrase:     process.env.YCSECRETPHRASE,
          appEmailAddress:  process.env.YCAPPEMAILADDRESS,
          appEmailPassword: process.env.YCAPPEMAILPASSWORD
       }
     module.exports = envGlobalObj

    Then in the files I wish to reference this object, I added a require statement.

     var envGlobalObj = require("./envGlobalObj.js");

    This allowed me to centralize the environment and secrect variables.

    0 讨论(0)
提交回复
热议问题