Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 定义变量的scopre_Javascript_Jquery_Scope - Fatal编程技术网

Javascript 定义变量的scopre

Javascript 定义变量的scopre,javascript,jquery,scope,Javascript,Jquery,Scope,所以我有下面的基本脚本,用于在整个项目中使用的常见函数。让我们用下面的代码调用这个base.js base.js (function(document, window, undefined, $){ if (typeof $ === undefined) { throw new Error("Site requires jQuery"); } $.SPA = {}; $.SPA.showAlert = function(msg) {

所以我有下面的基本脚本,用于在整个项目中使用的常见函数。让我们用下面的代码调用这个base.js

base.js

(function(document, window, undefined, $){

    if (typeof $ === undefined) {
        throw new Error("Site requires jQuery");
    }

    $.SPA = {};

    $.SPA.showAlert = function(msg) {
      alert(msg);
    };

})(document, window, undefined, jQuery);
$(function() {
    $.SPA.showAlert("Bazzinga");
});
我可以在特定页面中加载不同的脚本

现在假设我有一个页面,比如dashboard,它加载带有以下代码的dashboard.js

dashboard.js

(function(document, window, undefined, $){

    if (typeof $ === undefined) {
        throw new Error("Site requires jQuery");
    }

    $.SPA = {};

    $.SPA.showAlert = function(msg) {
      alert(msg);
    };

})(document, window, undefined, jQuery);
$(function() {
    $.SPA.showAlert("Bazzinga");
});
因此,我可以毫无问题地访问
$.SPA
。但我的问题是,这是正确的还是可能导致
$.SPA
范围出现问题,或者有可能从其他脚本重写它

但我的问题是,这是正确的还是可能导致$SPA出现问题 作用域或是否有可能从其他脚本重写它

$。SPA
在全局范围内,因为
$
具有全局范围

是的,其他脚本可以覆盖它,因为它们也可以访问这个变量,这对于JavaScript中的大多数对象都是正确的,因为它被设计为可扩展的

您可以使用

在你生命的最后加上这一行

(function(document, window, undefined, $){

    if (typeof $ === undefined) {
        throw new Error("Site requires jQuery");
    }

    $.SPA = {};

    $.SPA.showAlert = function(msg) {
      alert(msg);
    };

    Object.freeze($.SPA);

})(document, window, undefined, jQuery);
编辑:

根据@ArunPJohny的评论,您还需要使用define属性,因为单靠冻结是不够的

(function(document, window, undefined, $){

    if (typeof $ === undefined) {
        throw new Error("Site requires jQuery");
    }

    $.SPA = {};

    $.SPA.showAlert = function(msg) {
      alert(msg);
    };
    Object.defineProperty($, 'SPA', {
     enumerable: true,
     configurable: false,
     writable: false,
     value: {}
   });    

    Object.freeze($.SPA);

})(document, window, undefined, jQuery);

任何脚本都可以覆盖它。。但这就是我们所能做的。。。另一个解决方案是在现代浏览器中使用并使其成为不可写的值only@ArunPJohny根据我指出的文档,它将防止,只是它不会抛出错误。要抛出错误,必须启用严格模式。文档是正确的,它只是冻结分配给
SPA
属性的对象,我们仍然可以写入
$
SPA
属性。。。因此,仅仅使用
freeze
无法解决问题。。。。您需要定义属性,使其不是writable@ArunPJohny谢谢,进行了更改以解决浅冻结问题