如何让跨多个文件的多个 JavaScript 对象访问同一个私有变量? [英] How do I give multiple JavaScript objects across multiple files access to same private variable?

查看:29
本文介绍了如何让跨多个文件的多个 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 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.part01app.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 中,在该 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天全站免登陆