这个“(function(){});”,括号内的函数是什么意思在javascript? [英] What does this "(function(){});", a function inside brackets, mean in javascript?

查看:640
本文介绍了这个“(function(){});”,括号内的函数是什么意思在javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

这是什么意思? (function(x,y)){…}){a,b);在JavaScript中


您好全部



我不知道以下内容:

 (function(){
// Do something here
...
})(someWord)//为什么是这里?

我的问题是:


  1. 将函数放在方括号中的意思是什么(function(){});

  2. 在函数的末尾,括号是做什么的? >

我通常在jQuery代码和其他一些javascript库中看到这些。

解决方案

您立即调用具有特定参数的匿名函数。



例如:

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



此提醒 peter



的jQuery,你可以传递 jQuery 作为参数,并在你的函数中使用 $ 。所以你仍然可以在noConflict模式下使用jQuery,但使用方便的 $

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


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 the 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)

这篇关于这个“(function(){});”,括号内的函数是什么意思在javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆