JS:隐藏其他脚本的变量

JS: Hide variable for other scripts

本文关键字:变量 脚本 其他 隐藏 JS      更新时间:2023-09-26

在scriptA中,我有以下代码:

var John = 'Doe';

在脚本 B 中:

alert(John);

但是我不希望共享 2 个脚本之间的变量,如何隐藏 scriptB 的 John 变量?提前感谢!

您可以使用匿名函数来隐藏变量:

<script>
    (function(){
        var John = 'Doe';
    })();
</script>
类似的块可以

重复,但变量在该块中可以具有不同的值:

<script>
    (function(){
        var John = 'AnotherValue';
    })();
</script>
您可以通过将

变量放入 IIFE(立即调用的函数表达式)中来"隐藏"变量,如下所示:

(function() {
    // this variable is only accessible within this function block
    var John = "Doe";
})();
// this causes an error because the variable John is not available outside the IIFE
alert(John);

这将创建一个立即执行的私有函数作用域。 这是一种常见的设计模式,用于声明具有本地用途的变量,但您不希望广泛共享,也不想污染全局命名空间或与之冲突。