开发者

What does this "(function(){});", a function inside brackets, mean in javascript? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicates:

What does this mean? (function (x,y)){…}){a,b); in JavaScript

What do parentheses surrounding a JavaScript object/function/class declaration mean?

Hi All

I don't know what the following does:

(function(){
  // Do something here
  ...
})(someWord) //Why is this here?;

My questions are:

  1. What's the meaning of putting a function inside brackets .i.e. (function(){});?
  2. What do the set of brackets do at th开发者_JAVA百科e end of a function?

I usually see these in jquery codes, and some other javascript libraries.


You're immediately calling an anonymus function with a specific parameter.

An example:

(function(name){
  alert(name);
})('peter')

This alerts "peter".

In the case of jQuery you might pass jQuery as a parameter and use $ in your function. So you can still use jQuery in noConflict-mode but use the handy $:

jQuery.noConflict()
(function($){
  var obj = $('<div/>', { id: 'someId' });
})(jQuery)


You are making a function that is immediately being called, with someWord as a parameter.


It's a way to define an anonymous function and then immediately executing it -- leaving no trace, as it were. The function's scope is truly local. The () brackets at the end execute the function -- the enclosing brackets are to disambiguate what is being executed.


Basically this lets you declare an anonymous function, and then by enclosing it in parentheses and writing (someWord) you are running the function. You could think of it as declaring an object and then immediately instantiating the object.


It's used to create anonymous function (function without name that can be "nested" inside other function) and pass argument to that function. The someWord is passed as argument, and the function can read it using the keyword "arguments".

Simple example of usage:

function Foo(myval) {
    (function(){
      // Do something here
      alert(arguments[0]);
    })(myval); //pass myval as argument to anonymous function
}
...
Foo(10);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜