(function(){...})() 与 (function(){...}())

前端开发:立即执行函数(function(){}())与(function(){})()的区别 声明一个函数,然后立即调用该函数,这时候的该函数就是一个立即执行函数,换句话说就是声明函数以后立即执行该函数就叫做立即执行函数,即IIFE (Immediately Invoked Function Expression)。通常立即执行函数会以匿名函数的形式来声明,匿名函数的写法格式为function(){},即使用关键字function来声明函数,且未给该函数命名,但是匿名函数不能直接单独使用,需要使用小括号()包裹起来,不然就会报错。立即执行函数的作用大概有三个方面:1、为了避免污染全局变量,声明函数不 阅读详情

JS中函数有两种命名方式

1、一种是声明式。

而声明式会导致函数提升,function会被解释器优先编译。即我们用声明式写函数,可以在任何区域声明,不会影响我们调用。

function XXX(){}
  • 1
  • 1
2、一种是函数表达式

函数表达式我们经常使用,而函数表达式中的function则不会出现函数提升。而是JS解释器逐行解释,到了这一句才会解释。因此如果调用在函数表达式之前,则会调用失败。

var k = function(){}
  • 1
  • 1
fn1();
function fn1(){}//可以正常调用

fn2();
var fn2 = function(){}//无法调用
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

OK,下面进入正题,对函数表达式加上(),是可以直接调用的 
但是如果是对声明式的后部加上()则是会被编译器忽略。

 var fn2 = function(){}();//对,就是这样
function fn1(){}();//会被忽略
  • 1
  • 2
  • 1
  • 2

而平常的function(){}则是一种声明式,如果加上()括号后,则会被编译器认为是函数表达式,(加上+-号都可以),从而可以用()来直接调用

(function fn1(){})();

二
function foo() {...}     // 这是定义,Declaration;定义只是让解释器知道其存在,但是不会运行。

foo();                   // 这是语句,Statement;解释器遇到语句是会运行它的。

IIFE 并非必须,传统一点可以这么写:

function foo() {...}
foo();

那么为什么要 IIFE?

  1. 传统的方法啰嗦,定义和执行分开写;
  2. 传统的方法直接污染全局命名空间(浏览器里的 global 对象,如 window)

于是,开发者们想找一个可以解决以上问题的写法。那么像下面这么写行不行呢?

function foo(...){}();

当然是不能,但是为什么呢?因为 function foo(...){} 这个部分只是一个声明,对于解释器来说,就好像你写了一个字符串 "function foo(...){}",它需要使用解析函数,比如 eval() 来执行它才可以。所以把 () 直接放在声明后面是不会执行,这是错误的语法。

如何把它变得正确?说起来也简单,只要把 声明 变成 表达式(Expression) 就可以了。

实际上转变表达式的办法还是很多的,最常见的办法是把函数声明用一对 () 包裹起来,于是就变成了:

(function foo() {...})    // 这里是故意换行,实际上可以和下面的括号连起来
();

这就等价于:

var foo = function () {...};    // 这就不是定义,而是表达式了。
foo();

但是之前我们说不行的那个写法,其实也可以直接用括号包起来,这也是一种等价的表达式:

(function foo(){...}());

所以你问有没有区别?很简单:木有~

另外,刚才说过转变表达式的方式很多,的确还有很多别的写法,比如:

!function foo() {...}();

或者

+function foo() {...}();

这些都可以。

我个人挺偏爱用 void 来转变表达式,因为此关键字不会有返回值。不过这一点真的没有什么要紧的,就当我“龟毛”好了……

void function () {
    // 这里是真正需要的代码
}();

OK,所谓不去污染全局命名空间,是因为 IIFE 创建了一个新的函数作用域,你真正的业务代码被封装在其中,自然就不会触碰到全局对象了。如果你需要全局对象,那就 pass 给 IIFE:

void function (global) {
    // 在这里,global 就是全局对象了
}(this)    // 在浏览器里,this 就是 window 对象


$(document).ready(function() {})不执行初始化脚本 今天发现一个页面始终不执行$(document).ready(function() {})初始化脚本,下面是解决方法 立即下载

相关推荐

从STM32转战华大HC32F4A0:我的踩坑实录与10个USART的灵活配置心得

本文分享了从STM32迁移至华大HC32F4A0的实战经验,重点解析了10个USART的灵活配置技巧及常见问题解决方案。通过对比STM32F407,详细介绍了HC32F4A0在外设灵活性、IO功能组设计及多串口应用中的优势,帮助开发者快速掌握国产芯片的开发要点。

weixin_30514745的博客 523

函数高级应用

一、函数的定义方式 (1)、函数声明 function fn(){ console.log('this is a function') } (2)、函数表达式 var fn = function(){ console.log('赋值表达式函数') } (3)、内置构造函数的形式 varfn3=newFunction("num1","num2","returnnum1+num2"); console.log(fn3(2,3)); 推荐使用第二种形式,第三...

zzzlln的博客 664

cs188Inference in Bayes Nets(贝叶斯网络的推理)

cs188Inference in Bayes Nets贝叶斯网络的推理Question1(3 points):Bayes Net StructureQuestion2(1 points):Bayes Net ProbabilitiesQuestion 3(5 points):Join FactorsQuestion4(4 points):EliminateQuestion5(4 points):NormalizeQuestion 6(4 points):Variable EliminationQuesti

weixin_46582817的博客 1673

(function(){})()立即执行函数

来源 |https://www.fly63.com立即执行函数(function(){})()关键词:立即执行函数 匿名函数 作用域格式:(function())()作用:立即执行函数(function())()是匿名函数, 主要利用函数的作用域, 减少全局变量的使用。解释前提知识js中的函数通常有两种命名方式,分别是声明式函数 和 函数表达式。// 声明式函数 ...

web前端开发 600

别再到处找密钥了!手把手教你搞定Halcon 24.11/25.05的试用授权(附每月更新提醒)

本文详细介绍了Halcon 24.11/25.05试用授权的获取与配置方法,包括解密新版授权机制、快速配置指南、每月更新规律及多版本共存管理技巧。帮助开发者避免常见授权问题,提升工作效率,特别适合机器视觉领域的初学者和专业人士。

weixin_29238147的博客 1148

S4-FPGA-K7板级原理图硬件实战

xilinx K7板级硬件实战

weixin_66510961的博客 6149

理解javascript中的立即执行函数(function(){})()

本文章转载自:https://www.cnblogs.com/yanzp/p/6371292.html 感谢分享 理解javascript中的立即执行函数(function(){})() 之前看了好多代码,都有用到这种函数的写法,但是都没认真的去想为什么会这样写,今天开始想学习下jquery的源码,发现jquery也是使用这种方式,用(function(window, undefined){})(...

Darkness的博客 990

手把手教你用ZEMAX复现贝塞尔光束:从Thorlabs锥透镜到Edmund透镜的完整光路搭建

本文详细介绍了如何在ZEMAX光学设计软件中复现贝塞尔光束,从Thorlabs锥透镜到Edmund透镜的完整光路搭建过程。通过逐步指导,帮助研究人员和工程师掌握光学设计技巧,实现无衍射特性的贝塞尔光束生成,适用于激光加工和生物成像等领域。

weixin_33737774的博客 179

var与function声明提升的区别-你必须知道的知识点

面试的时候遇到过这么一道题 (() => { console.log(a); //当时我的答案:undefined 正确答案:ƒ a(){} var a = 10; console.log(a); //10 a = 20; function a(){}; console.log(a); //我的答案:ƒ a(){} 正确答案:20 })() 当时完全没有想明白,为什么第一次打印是个function,最后一次打印怎么又变成20了?经过几番查证思考,终于想

lancecool的博客 1227

ByteTrack参数调优全攻略:从原理到实战(含YOLOv8示例)

本文深入解析了ByteTrack多目标跟踪算法的核心原理与参数调优策略。通过拆解其独特的两阶段关联机制,并结合YOLOv8检测器,提供了针对不同应用场景(如拥挤行人、高速车辆)的精细化参数调整指南与实战示例,旨在帮助开发者解决ID切换、目标丢失等工程落地难题,提升跟踪系统的鲁棒性与实用性。

cheese的博客 322

【Burp入门第二篇】Chrome配置BurpSuite代理教程

1、配置Burp代理为127.0.0.1:80802、扩展商店添加插件switchyomega,修改服务器和端口为下图:3、打开代理,选择刚才添加的代理

等风来 8368

(function(){}()),(function(){})(),$(function(){});之间的区别

(function(){}()),(function(){})(),$(function(){});之间的区别

dijxv的博客 882

28-手把手教你手写CPU-Verilog - 乘法器设计:Booth算法与Wallace树乘法器

文章摘要: 本文详细介绍了两种高效乘法器设计方法:Booth算法和Wallace树乘法器。Booth算法通过检测乘数连续1/0减少部分积,适合有符号数运算;Wallace树采用树形结构压缩部分积,显著降低延迟。文章包含算法原理、具体示例、Verilog实现代码(4位乘法器)及性能对比表,指出Booth适用于通用处理器,Wallace树更适合高性能DSP/GPU。最后强调实际设计中需根据速度、面积和功耗需求选择合适方案。

2301_79143213的博客 206

(function(){}())与(function(){})()

以后再说

zyc050707的博客 235

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

(function(){}())与(function(){})()的区别

1. (function(){}())与(function(){})() 这两种写法,都是一种 立即执行函数 的写法,即IIFE (Immediately Invoked Function Expression)。这种函数在函数定义的地方就直接执行了。 通常的函数声明和调用分开的写法如下: function foo() {/*...*/} // 这是定义,Declaration;定义只...

米洛尔的博客 9252

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

JavaScript (function (){}()) 与(function(){})()

function(){} 可以理解为它是一个定义的方法 只是让浏览器知道 有这么一个存在 并不会执行 执行时要带() 一般我们都会这样子写 var a=function(){} ; a(); 如果要整合写的话 那么就是 (function(){})() 这样子就相当于var a=function(){} ; a(); 定义了方法 并且执行了 如果你不写functio...

weixin_30398227的博客 194

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

js (function(){}())与(function(){})()自启动函数

(function(){}())与(function(){})() 这两种写法,都是一种立即执行函数的写法,即IIFE (Immediately Invoked Function Expression)。这种函数在函数定义的地方就直接执行了。 ...

weixin_43294560的博客 524

Javacript中(function(){})() 与 (function(){}()) 区别 {转}

这个问题可以从不同的角度来看,但从结果上来说 :他们是一样的。首先,如果从AST(抽象语法树)的角度来看,两者的AST是一模一样的,最终结果都是一次函数调用。因此,就解析器产生的结果论而言,两者是没有区别的。 其次 ,从作用上看,前文已经说了,两者的作用都是创建一个函数并调用之。那么为什么要创建一个函数并立即调用呢,我想大多数是因为javascript的代码默认在全局环境下执行,在此声明的所有变...

weixin_34235371的博客 332

(function(){...}())与(function(){...})()

  (function(){         ......   }())  或   (function(){            ......   })()    匿名函数自调用,也就是说,定义一个匿名函数,然后马上调用它。 因为这个匿名函数的函数体相当于提供一个匿名的名字空间,这样就不会与用户自定义的JS函数、变量、对象发生冲突了,不失为是一种很好的解决命名空间问题的方法。 ...

weixin_33757911的博客 143

js中自执行函数(function(){})()和(function(){}())区别

方式一,调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用在去调用执行方式二,调用函数,得到返回值。强制运算符使函数调用执行(function(){})(); 是 把函数当作表达式解析,然后执行解析后的函数相当于 var a = function(){}; a(); a得到的是函数(function(){}()); 是把函数表达式和执行当作语句直接执行、相当于 var a = funct...

weixin_33946605的博客 2454

立即执行函数: (function(){...})() 与 (function(){...}()) 有什么区别?

没有区别。 定义函数有两种方式:一种是函数声明,另一种是函数表达式.函数声明: function foo(arg0,arg1,arg2){ //函数体 }函数表达式: var foo = function (arg0,arg1,arg2){ //函数体 ...

weixin_33921089的博客 93

立即执行函数: (function(){...})() 与 (function(){...}())

你需要明白 IIFE 的原理,我简单说一下: function foo() {...} // 这是定义,Declaration;定义只是让解释器知道其存在,但是不会运行 foo(); // 这是语句,Statement;解释器遇到语句是会运行它的。 IIFE 并非必须,传统一点可以这么写: function foo() {...} f...

iteye_4180的博客 114
上一篇: socket.io 中文文档
下一篇: react引入公用js文件
function__
博客等级 码龄10年 99粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值