一个 JavaScript 函数
请解释以下在 javascript 函数中编写函数的方法:
(function (){
// some code
})()
我知道由于尾部大括号“ () ”,该函数将立即执行,但是将函数括在大括号中意味着什么?
Please explain the following way of writing a function in javascript functions :
(function (){
// some code
})()
I understand the fact that because of the trailing braces " () ", the function will execute immediately but but what does enclosing the function in the braces mean?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的语法不正确。编辑:已修复。
看一下您只想调用一次且仅一次的普通函数定义:
您可以减少此代码,以便立即执行它,无需将其命名为 add:
注意我们是如何包围的该函数带有一组括号,使其成为可调用表达式。此模式通常用于创建某些变量的闭包(捕获其状态),例如:
Your syntax is incorrect. Edit: fixed.
Look at a normal function definition that you want to call once and only once:
You could reduce this code so that you execute it straight away, there is no need to name it add:
Note how we have surrounded the function with a set of parenthesis to make it a callable expression. This pattern is often used to create a closure (capture the state of) certain variables, for example:
正如 RobG 指出的,这是您原始问题中唯一有效的陈述选择。
它在解析后立即执行,并提供了一种将函数内的代码从其余代码中排除的方法。这称为闭包(请参阅MDN 上的闭包 )并且可以帮助解决脚本中的内存泄漏。
As RobG pointed out, this is the only valid statement choice in your original question.
This is executed right after it is parsed, and provides a way to out-scope the code inside the function from the rest of your code. This is called a closure (see Closures on MDN) and may help with memory leaks in your scripts.
将代码包含在分组运算符中会将其从函数声明更改为函数表达式(其中名称是可选的并且通常被省略)。该模式通常称为“立即调用函数表达式”(iife) 或“立即执行函数表达式”(iefe)。
它用于替换仅被调用一次的函数声明。它也是模块模式的基础。
Enclosing the code in a grouping operator changes it from a function declaration to a function expression (where the name is optional and usually omitted). That pattern is often called an "immediately invoked function expression" (iife) or "immediately executed function expression" (iefe).
It is used to replace a function declaration that is called just once. It is also fundamental to the module pattern.