简体   繁体   English

这个javascript片段实际上是什么意思?

[英]What actually does this javascript snippet mean?

From HTML5 Mobile Boilerplate's helper.js: HTML5移动样板的 helper.js:

(function(document){
    //all stuff here
})(document);

What does this snippet do or when does it run? 此代码段是做什么的或何时运行?

This is a closure, it defines a method which takes an argument document and immediately calls it with document as the parameter. 这是一个闭包,它定义了一个方法,该方法接受参数document并立即以document作为参数来调用它。

It runs as soon as it's finished evaluating - so basically straight away. 它会在完成评估后立即运行-因此基本上可以立即进行。

It creates a temporary, anonymous function and calls it with an argument called document. 它创建一个临时的匿名函数,并使用名为document的参数调用它。 Presumably it has some local variables that it is hiding from the enclosing scope. 大概它有一些局部变量正在从封闭范围中隐藏。

This is a javascript function that executes immediately when the browser encounters it while parsing the page. 这是一个javascript函数,当浏览器在解析页面时遇到它时,将立即执行该函数。 The function takes one parameter, which is the window.document property (as passed in at the bottom of the function. 该函数采用一个参数,即window.document属性(在函数底部传入)。

If you say: 如果你说:

(function(var1){/*stuff*/})(var2)

That immediately calls the function and passes var2 to the function. 立即调用该函数并将var2传递给该函数。 Note that the function is anonymous and cannot be called directly. 请注意,该函数是匿名的,不能直接调用。 You can read about anonymous functions in general and anonymous functions in Javascript here: 您可以在此处阅读有关常规匿名函数和Javascript匿名函数的信息:

http://en.wikipedia.org/wiki/Anonymous_function#JavaScript http://en.wikipedia.org/wiki/Anonymous_function#JavaScript

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

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