簡體   English   中英

如何在不同的JS文件之間共享相同的作用域變量

[英]How to share same scope variables between different JS files

我有三個腳本文件。 main.js,script1.js,script2.js。

main.js只是將該腳本包含在文檔中:

function IncludeJs(sFileName) {
    document.writeln('<script type="text/javascript" src="' + sFileName + '"></script>');
}

IncludeJs("../script1.js");
IncludeJs("../script2.js");

script1.js和script2.js代碼位於同一命名空間下。

script1.js:

var sharedNamespace = sharedNamespace || {}; 

(function () {

    "use strict";

     function func1(){
        ....
     }

}).apply(sharedNamespace );

script2.js:

var sharedNamespace = sharedNamespace || {}; 

(function () {

    "use strict";

     function func2(){
        return func1();
     }

}).apply(sharedNamespace );

func2不起作用,因為func1未定義。 我如何才能將script1.js和script2.js與共享變量置於同一范圍內?

對我來說, sharedNamespace.func1 = function(){}的解決方案最糟糕,因為我不想將此功能公開給使用我的庫的客戶端...

...我不想向使用我的圖書館的客戶公開此功能...

如果要使用單獨的腳本文件,並且希望它們定義相互調用的函數,則別無選擇。 不可能讓script1.jsscript2.js共享一個公共范圍,該范圍也無法被頁面上的其他腳本訪問。

相反,您可能希望將用於開發的單獨文件合並以進行部署,因為單個腳本可以(當然)可以具有私有信息。 (當然,除非用戶編輯腳本,否則為私人。)

因此,例如,您可能會遇到以下情況:

script1.js

var internal = internal || {};
(function(i) {
    i.func1 = function func1() {
        // ...code here, possibly using i.func2()
    };
})(internal);

script2.js

var internal = internal || {};
(function(i) {
    i.func2 = function func2() {
        // ...code here, possibly using i.func1()
    };
})(internal);

在進行開發時,您將它們分別包含在內,因此任何代碼都可以使用internal.func1 但是,當您執行多合一腳本構建時,您需要將其包裝

(function() {
    // ...contents of script1.js here...
    // ...contents of script2.js here...
})();

現在, internal對組合腳本是私有的。

那是我的頭頂。 可能不那么麻煩

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM