Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

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

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, if I have the following code:

APP = (function () {
    var _secret = {},
        app = {};
    // Application part 01:
    app.part01 = (function () { /* function that uses _secret */ }());
    // Application part 02:
    app.part02 = (function () { /* function that uses _secret */ }());
    //
    return app;
}());

How do I put app.part01 and app.part02 in seperate files, but still have access to _secret? I don't want to pass it as an argument. That's just giving the secret away, as app.part01() could be replaced by any other function.

Maybe I am asking the impossible, but your suggestions might lead me in the right way.

I want to work with multiple files, but I don't know how. Copying and pasting everything inside a single function each time before testing is not something I want to do.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...