简体   繁体   English

我应该在Java代码中的哪个位置放置函数?

[英]Where should I put functions in Javascript code?

I have the following code: 我有以下代码:

(function($) {
  "use strict";

  $(function() {
    // jQuery code here, eg:
    $('body').css('padding-top', $('.nav').height());
    // I want to call that func here...
  });

}(jQuery));

And custom function: 和自定义功能:

function xyz(a,b) {
  // do something with "a" and "b"
}

Where should I place my custom function? 我应该在哪里放置自定义函数? Before (function($) { , before $(function() { , or inside $(function() {}); ? 之前(function($) {$(function() {之前或$(function() {});

The difference is the scope. 区别在于范围。

Location              :  Scope
----------------------+--------------------------------------------------------
before (function($) { :  in global scope, easy to call & modify from everywhere 
before $(function() { :  in "source module" scope / jQuery closure
inside $(function() { :  in "$(function" scope 

So that choice gives you the means to organize the access to your code. 因此,这种选择使您可以组织访问代码的方式。 In most cases you want to hide stuff to prevent unintended interactions, but in some cases (eg log function), you want to have access from everywhere in your web application. 在大多数情况下,您希望隐藏内容以防止意外的交互,但是在某些情况下(例如,日志功能),您希望可以从Web应用程序中的任何位置进行访问。

If you do not need to call xyz() from outside $(function , keep it inside. If you do just need to call it within the module, keep it inside ( .. (jQuery)) . If you need to call it from everywhere keep it outside in global scope. 如果您不需要从$(function外部调用xyz() ,请将其保留在内部。如果只需要在模块内部调用它,请将其保留在内部( .. (jQuery)) 。各地都将其排除在全球范围之外。

Since you want to call the function inside the ready handler, declare it inside it 由于您要在ready处理程序中调用该函数,因此请在其中声明它

jQuery(function ($) {
    "use strict";

    // jQuery code here, eg:
    $('body').css('padding-top', $('.nav').height());
    // I want to call that func here...
    xyz();

    function xyz(a, b) {
        // do something with "a" and "b"
    }
});

But if you want to access xyz from outside the scope of the dom ready handler you will have to declare it outside the scope of the dom ready handler. 但是,如果要从dom ready处理程序范围之外访问xyz ,则必须在dom ready处理程序范围之外声明它。 Now the method is local to the dom ready handler and thus accessible only inside it. 现在,该方法在dom ready处理程序本地,因此只能在其内部访问。

Also as shown above you can shorten the use of IIFE and dom ready handler as shown above 同样如上所示,您可以缩短如上所示的IIFE和dom ready处理程序的使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM