简体   繁体   中英

Meaning of statement in JS

Trying to figure out what this means in javascript.

(function(document) { ... } )(document);

It is isn't using jQuery, so is this just a javascript way of making this wait till document is ready to execute? Thanks.

This won't wait for the document to be ready, this will execute the content of the function immediately. Putting the function definition in parenthesis makes it an expression, which returns a value being the function, making it directly executable. This pattern is called an Immediately-Invoked Function Expression (IIFE) .

This is probably used in conjunction with a minifier like the Closure Compiler .

Inside the function, document is a local variable. This makes it possible for the minifier to reduce its name to a one or two character name.

Note also that all variables defined inside the function will be local : they won't leak in the global scope, which may be interesting if this is only part of the script.

这将创建一个接受单个参数的匿名函数,并立即将其作为document传递给document

This:

function(document) { ... } 

creates a function taking one paremeter.

This:

(function(document) { ... })

makes it (the code, not the function) a valid expression. See here .

This:

(function(document) { ... } )(document);

calls that function with document as a parameter.

It's a basic modularization pattern. In different environments you could've passed some other object instead of document, but nothing inside that function has to know bout it.

This is called self-executed function . It evaluates the anonymous function taking a parameter called document with that parameter passed in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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