jquery - scope inside $(document).ready()?

前端 未结 2 1193
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 01:51

So to stay organized, I have several javascript files, even though they all (in the end) are minified together to form one final javascript file.

Each file\'s conten

2条回答
  •  -上瘾入骨i
    2020-12-03 02:27

    Javascript uses functional scopes, so local variables inside a function are not visible to the outside. This is why your code can't access code from other scopes.

    The ideal solution to this is create a Namespace.

    var NS = {};
    
    (function(){
      function privateFunction() { ... }
      NS.publicFunction = function(){ ... }
    })();
    
    $(document).ready(function(){
      NS.publicFunction();
    });
    

    This is also a useful pattern because it allows you to make a distinction between private & public elements.

提交回复
热议问题