简体   繁体   English

需要一些帮助来了解此JavaScript

[英]Need some help understanding this JavaScript

I have the following strange looking code in a js file and i need some help in understanding whats going on. 我在js文件中有以下看起来很奇怪的代码,我需要一些帮助来了解发生了什么。 What im confused about is why is the whole thing put in paranthesis ?. 令我感到困惑的是,为什么整个事情都陷入了偏瘫? What does that mean ? 这意味着什么 ?

(function() {
  var someobj = window.someobj = [];
  var parentId = '#wrapper';

  $(document).ready(function() {
    //some code here
    });


  $(document).ready(function() {
    //some code here    
      }
    });

If the code that you provided is complete (with the exception of what is inside the two $(document).ready(function() {}); statements), than this code does nothing and the function is never executed. 如果您提供的代码是完整的(两个$(document).ready(function() {});语句中的内容除外),则此代码将不执行任何操作,并且该函数将永远不会执行。 It's the same with or without the wrapping parenthesis. 带有或不带有括号的情况都是一样的。

By wrapping a function in parenthesis, you can create an anonymous function . 通过将函数包装在括号中,可以创建匿名 函数 However, the function must be executed immediately, or stored in a variable (which would negate the anonymous part). 但是,该函数必须立即执行或存储在变量中(这将否定匿名部分)。 You'll often see this technique to avoid polluting the global scope with variables that are temporary or only used for initialization of a larger application. 您将经常看到这种技术,可以避免使用临时变量或仅用于大型应用程序初始化的变量污染全局范围。 For example. 例如。

(function() {
  // Do initialization shtuff
  var someLocalVariable = 'value';
})(); 
// Notice the `();` here after the closing parenthesis.  
// This executes the anonymous function.

// This will cause an error since `someLocalVariable` is not 
// available in this scope
console.log(someLocalVariable);

So then, what your code is missing is the (); 因此,您的代码丢失了(); after the closing parenthesis at the end of the function. 函数结尾处的右括号后。 Here is what your code should (presumably) look like: 这是您的代码应该(大概)如下所示:

(function() {
  var someobj = window.someobj = [];
  var parentId = '#wrapper';

  $(document).ready(function() {
    //some code here
  });


  $(document).ready(function() {
    //some code here    
  });
})();

It does not look like this code is complete. 该代码看起来不完整。 As written, this code will do nothing at all. 如所写,此代码将完全不执行任何操作。 Are you missing a close paren and an extra set of parentheses at the end? 最后是否缺少紧密的括号和额外的括号?

In JavaScript, there is no module system, and thus no way to create a module with its own top-level definitions that don't conflict with other modules that might be used. 在JavaScript中,没有模块系统,因此没有办法用自己的顶级定义创建一个模块,该定义与可能使用的其他模块不冲突。

In order to overcome this, people use anonymous function definitions to avoid name conflicts. 为了克服这个问题,人们使用匿名函数定义来避免名称冲突。 What you do is create an anonymous function, and execute it immediately. 您要做的是创建一个匿名函数,并立即执行它。

(function () { /* do stuff */ })();

This creates a function, and then executes it immediately with no arguments. 这将创建一个函数,然后立即不带参数地执行它。 Variables defined using var within that function will not conflict with variables defined anywhere else, and thus you get the equivalent of your own, private namespace, like what a module system would provide. 在该函数中使用var定义的变量不会与其他位置定义的变量冲突,因此,您将获得自己的私有名称空间的等效项,例如模块系统将提供的名称空间。

The outer parentheses are redundant here (there is a typo in your code though, I think you're missing the closing ); 外部括号在这里是多余的(尽管您的代码中有一个错别字,但我认为您错过了结尾); ). )。 Sometimes people will wrap a function in parentheses for clarity when invoking the function immediately, eg 有时,人们在立即调用该功能时会在括号内将其包装起来,以使其更加清晰。

(function($) { 
    //some jQuery code    
})(jQuery);

Within the function above, the parameter $ will have the value of the outer jQuery variable. 在上面的函数中,参数$将具有外部jQuery变量的值。 This is done within jQuery and jQuery plugins to prevent the $ symbol clashing with other frameworks. 这是在jQuery和jQuery插件中完成的,以防止$符号与其他框架冲突。

I'm going to assume that this is actually part of an anonymous function definition and that's why it's in parenthesis. 我将假定这实际上是匿名函数定义的一部分,这就是为什么要放在括号中。 I could see doing this if there was some sort of logic going to make window.someobj change based on different conditions, but have code further along do the same thing. 如果有某种逻辑可以使window.someobj根据不同的条件进行更改,那么我可以看到这样做,但是让代码继续执行相同的操作。

The parenthesis aren't actually necessary as far that this code goes. 就此代码而言,实际上并不需要括号。 This code doesn't seem complete though. 这段代码似乎并不完整。 The function initializes by setting a variable to some object on the page and then setting another constant. 该函数通过将变量设置为页面上的某个对象然后设置另一个常量来进行初始化。 Then there are two seemingly identical triggers that will trigger some code on page load. 然后有两个看似相同的触发器,它们将在页面加载时触发一些代码。

Doesn't seem like a very useful piece of code. 看起来好像不是非常有用的代码。 Is there some larger portion that might shed some light on this? 是否有更大的部分可能对此有所启发?

在JS中,您可以声明一个函数,然后自动调用它:

( function Test() { alert('test'); } )();

The parentheses define a temporary scope. 括号定义一个临时范围。 It is sometimes useful to do so in JavaScript. 有时在JavaScript中这样做很有用。 There are a number of examples and further explanation in John Resig's excellent guide to learning advanced JavaScript: John Resig出色的学习高级JavaScript的指南中有许多示例和进一步的解释:

http://ejohn.org/apps/learn/#57 http://ejohn.org/apps/learn/#57

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

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