如何在多个文件中为多个JavaScript对象提供对同一私有变量的访问权限? [英] How do I give multiple JavaScript objects across multiple files access to same private variable?

查看:68
本文介绍了如何在多个文件中为多个JavaScript对象提供对同一私有变量的访问权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在多个源文件中跨越我的JavaScript项目,但让每个文件都可以访问相同的私有变量,那么如何做到这一点?

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例如,如果我有以下代码:

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

如何将 app.part01 app.part02 在单独的文件中,但仍然可以访问_secret?
我不想将它作为参数传递。这只是给予秘密,因为 app.part01()可以被任何其他函数替换。

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.

推荐答案


如何将app.part01和app.part02放在单独的文件中,但仍然可以访问 _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

您正在寻找的是一个自动构建脚本。您将能够对其进行配置,以便将文件捆绑在一起,并将它们包装在IEFE中,在其范围内,它们将能够共享其私有状态。最简单的例子:

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

这篇关于如何在多个文件中为多个JavaScript对象提供对同一私有变量的访问权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆