从jQuery函数内部使函数公开

时间:2014-10-02 20:28:12

标签: javascript jquery

我有一块JavaScript / jQuery工作正常。

<script type="text/javascript">
    $(function () {
         function doSomething() {
             // Do something amazing here!
         }
        // Many various jQuery handlers and support functions
    });
</script>

但现在我希望我的doSomething()函数可以从同一页面上的另一个脚本块调用。

我知道我可以通过将doSomething()移到jQuery函数($(function () {}))之外来实现。但是doSomething()无法调用jQuery函数内的辅助函数。

我可以将其他函数移到jQuery函数之外,但是其中一些是需要初始化的处理程序,并且它们共享它们相同的辅助函数。

有没有办法将我的所有函数保存在我的jQuery函数中,但只是让它们中的一个可见?

关于我可以去哪里阅读的任何建议?

3 个答案:

答案 0 :(得分:2)

JavaScript具有功能范围。所以,如果它嵌套在

中你就无法调用你的函数
$(function () { ... });

是因为它只能在该函数的范围内访问。

您可以轻松移动功能定义

function doSomething() { ... }

$(function(){...})函数之外,并且仍然可以访问$(function(){...})函数范围内的变量,方法是将变量作为参数传递给函数,然后让它返回任何修改:

    $(function () {
         var blah = 'blah';
         var result;
         result = doSomething(blah);
         // Many various jQuery handlers and support functions
     });
     function doSomething(blah) {
         // Do something amazing here!
         return newBlah;
     }
     // Now you can call your doSomething function in the global scope too
     var example = "test";
     var result = doSomething(example);

答案 1 :(得分:0)

嗯,实际上你应该从这个包装器中移出你的逻辑。

它用于初始化应在DOM准备好后运行的逻辑。你不应该在这里做任何功能。

请考虑以下代码模式:

(function($) {
  // Your logic here
  // You could safely export your functions to
  // global scope from here, if you really need
  var app;

  app = {
    forms: doSomething
  };

  function doSomething() {
    // Do something amazing here!
  }

  window.app = app; 

  $(function() {/* start interact with DOM */});
}(jQuery));

答案 2 :(得分:0)

你可以扩展jQuery:

$.extend({
    foo: new function () {
        var _self = this;            

        _self.doSomething = function () {

        };   

        _self.initialize = function () {
            $('#button-x').click(function(){
                _self.doSomething(); //use the function inside
            }); 
        }; 
});

$(function () {
    $.foo.initialize();
    $.foo.doSomething(); //use the function outside
});
相关问题