外部脚本的可重用功能

时间:2011-01-02 10:00:39

标签: javascript jquery

简化示例:

// path/to/js/panel.js
$(function(){
    var hidePanel = function(){
        //hides the panel div
    };
});

// path/to/js/another-script.js
$(function(){
    hidePanel(); //out of scope MEGA-FAIL
});

正如我们所说,我将一些函数/变量复制粘贴在2个不同的文件中。 我很好奇RequireJS是否会解决这个问题......

2 个答案:

答案 0 :(得分:3)

你的函数本身只需要在加载jQuery之后声明如果它需要jQuery,但它不需要在document.ready上声明,只需执行然后。做你想做的事的最简单的方法是:

// path/to/js/panel.js
function hidePanel() {
 //hides the panel div
}

// path/to/js/another-script.js
$(hidePanel);

这只会将您的功能传递给$(), which schedules it run on document.ready, or immediately if the document is already ready

答案 1 :(得分:0)

// path/to/js/panel.js
$(function(){
    var hidePanel = function(){
        //hides the panel div
    };
});

使用此代码可以创建一个匿名函数。匿名函数不会污染全局命名空间。在匿名函数中声明的所有变量(在本例中为 hidePanel )在匿名函数之外是不可见的。 因此,该功能不可用。

所以你需要做一个全局功能。 你可以用不同的方式做到这一点:

var hidePanel = function() {
});

function hidePanel() {
}

P.S:我建议您学习javascript的OO模式: - ) Javascript Object-Oriented Programming | Part 1