search
HomeWeb Front-endJS TutorialSelf-executing function in js function

Self-executing function in js function

Jul 21, 2017 pm 05:05 PM
javascriptfunctionimplement

When I write code, I often write similar code in tpl's <script>: </script>

$(function(){
    alert("我好饿");
});

When I first started writing it, I only knew that it didn't need to be called, just directly Execution, just like this, I wrote a lot of code. Having said that, let’s talk about the loading sequence of this product. If you write the code directly into the script tag, the code inside the script tag will be executed when the page is loaded. If an unloaded DOM is used in this code or an unloaded method is called, an error will be reported. Closer to home, this function is actually a self-executing function. Many people will professionally call it "immediately called function expression".

Here, I quote limlimlim's blog, which feels more professional...original address

When you declare a function like function foo(){} or var foo = function(){} When, you can achieve self-execution by adding a bracket after it, such as foo(), look at the code:

// 因为想下面第一个声明的function可以在后面加一个括弧()就可以自己执行了,比如foo(),// 因为foo仅仅是function() { /* code */ }这个表达式的一个引用
 var foo = function(){ /* code */ } 
// ...是不是意味着后面加个括弧都可以自动执行?
 function(){ /* code */ }(); // SyntaxError: Unexpected token (//

The above code, if it even runs, the second code will error, because When the parser parses the global function or function internal function keyword, it defaults to a function declaration instead of a function expression. If you do not explicitly tell the compiler, it will declare a function without a name by default and throw A syntax error message because the function declaration requires a name.

What’s interesting is that even if you add a name to the wrong code above, it will prompt a syntax error, but the reason is different from the above. Adding parentheses () after an expression will execute the expression immediately, but adding parentheses () after a statement has a completely different meaning. It is just a grouping operator.

// 下面这个function在语法上是没问题的,但是依然只是一个语句// 加上括号()以后依然会报错,因为分组操作符需要包含表达式
 function foo(){ /* code */ }(); // SyntaxError: Unexpected token )
 // 但是如果你在括弧()里传入一个表达式,将不会有异常抛出// 但是foo函数依然不会执行function foo(){ /* code */ }( 1 ); 
// 因为它完全等价于下面这个代码,一个function声明后面,又声明了一个毫无关系的表达式: function foo(){ /* code */ }
 
( 1 );

To solve the above problem, it is very simple. We only need to use curly brackets to enclose all the code. Because statements cannot be included in brackets () in JavaScript, so in At this point, when the parser parses the function keyword, it will parse the corresponding code into a function expression instead of a function declaration.

// 下面2个括弧()都会立即执行(function () { /* code */ } ()); // 推荐使用这个(function () { /* code */ })(); // 但是这个也是可以用的// 由于括弧()和JS的&&,异或,逗号等操作符是在函数表达式和函数声明上消除歧义的// 所以一旦解析器知道其中一个已经是表达式了,其它的也都默认为表达式了// 不过,请注意下一章节的内容解释var i = function () { return 10; } ();true && function () { /* code */ } ();0, function () { /* code */ } ();// 如果你不在意返回值,或者不怕难以阅读// 你甚至可以在function前面加一元操作符号!function () { /* code */ } ();~function () { /* code */ } ();-function () { /* code */ } ();+function () { /* code */ } ();// 还有一个情况,使用new关键字,也可以用,但我不确定它的效率// new function () { /* code */ }new function () { /* code */ } () // 如果需要传递参数,只需要加上括弧()

The brackets mentioned above are used to disambiguate. In fact, they are not necessary at all, because the brackets are originally expected to be function expressions, but we still use them, mainly for It is convenient for developers to read. When you assign these automatically executed expressions to a variable, we will see the parentheses (() at the beginning. You can understand it quickly without having to pull the code to the end to see if there are any additions. Brackets.

In this post, we have always called it a self-executing function, to be precise, a self-executing anonymous function, but the original English author has always advocated its use. The author gave a bunch of examples to explain the name of Immediately-Invoked Function Expression. Well, let's take a look:

// 这是一个自执行的函数,函数内部执行自身,递归function foo() { foo(); }// 这是一个自执行的匿名函数,因为没有标示名称// 必须使用arguments.callee属性来执行自己var foo = function () { arguments.callee(); };// 这可能也是一个自执行的匿名函数,仅仅是foo标示名称引用它自身// 如果你将foo改变成其它的,你将得到一个used-to-self-execute匿名函数var foo = function () { foo(); };// 有些人叫这个是自执行的匿名函数(即便它不是),因为它没有调用自身,它只是立即执行而已。(function () { /* code */ } ());// 为函数表达式添加一个标示名称,可以方便Debug// 但一定命名了,这个函数就不再是匿名的了(function foo() { /* code */ } ());// 立即调用的函数表达式(IIFE)也可以自执行,不过可能不常用罢了(function () { arguments.callee(); } ());
(function foo() { foo(); } ());// 另外,下面的代码在黑莓5里执行会出错,因为在一个命名的函数表达式里,他的名称是undefined// 呵呵,奇怪(function foo() { foo(); } ());

Hope here Some examples can help everyone understand what is self-execution and what is immediate calling (I only understand a little bit here, long live the theory)

limlimlim also talked aboutModule mode## below. #, this is an important thing I need to learn in the future. Of course, there is closure before this (big head)

Let me show you an example

// 创建一个立即调用的匿名函数表达式// return一个变量,其中这个变量里包含你要暴露的东西// 返回的这个变量将赋值给counter,而不是外面声明的function自身var counter = (function () {var i = 0;return {
        get: function () {return i;
        },
        set: function (val) {
            i = val;
        },
        increment: function () {return ++i;
        }
    };
} ());// counter是一个带有多个属性的对象,上面的代码对于属性的体现其实是方法counter.get(); // 0counter.set(3);
counter.increment(); // 4counter.increment(); // 5counter.i; // undefined 因为i不是返回对象的属性i; // 引用错误: i 没有定义(因为i只存在于闭包)

The above is the detailed content of Self-executing function in js function. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.