Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.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 在生活中访问函数或变量_Javascript_Jquery_Iife - Fatal编程技术网

Javascript 在生活中访问函数或变量

Javascript 在生活中访问函数或变量,javascript,jquery,iife,Javascript,Jquery,Iife,我已经创建了一些JavaScript,我想将其包装在IIFE中,但我发现这很困难,因为JavaScript包含在不同JS文件中使用的变量和函数 例如: 我的app.js (function(window, document, $){ var currentArea; function changeAreaTo(value){ currentArea = $('.sp-spine-item:eq('+value+')'); } }(window, do

我已经创建了一些JavaScript,我想将其包装在IIFE中,但我发现这很困难,因为JavaScript包含在不同JS文件中使用的变量和函数

例如:

我的app.js

(function(window, document, $){

    var currentArea;

    function changeAreaTo(value){
        currentArea = $('.sp-spine-item:eq('+value+')');
    }

}(window, document, window.jQuery));
(function(window, document, $){

    changeAreaTo(3);
    $('html, body').scrollTop(currentArea.position().top);

}(window, document, window.jQuery));
外部app.js

(function(window, document, $){

    var currentArea;

    function changeAreaTo(value){
        currentArea = $('.sp-spine-item:eq('+value+')');
    }

}(window, document, window.jQuery));
(function(window, document, $){

    changeAreaTo(3);
    $('html, body').scrollTop(currentArea.position().top);

}(window, document, window.jQuery));
我的实际JS比上面的要复杂一些,但这让你对我要处理的事情有了一个基本的了解

my-app.js可以在多个项目中使用,但不应该针对每个项目进行修改,它有点像一个基本库


因此,我想知道外部JS文件在单独的生命周期中访问任何变量或函数的最佳方式是什么。

您需要做的就是返回您希望在另一个文件中访问的函数,并将其分配给全局可访问的对象

var changeAreaTo = (function(window, document, $){

    var currentArea;

    function changeAreaTo(value){
        currentArea = $('.sp-spine-item:eq('+value+')');
    }
    return changeAreaTo;

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

请看显示模块模式谢谢,这很有帮助!