search
HomeWeb Front-endJS TutorialIn-depth analysis of javascript immediate execution function_javascript skills

Javascript is more casual than other programming languages, so the JavaScript code is full of all kinds of weird writing methods, which sometimes appear in the fog;
Of course, being able to understand various types of writing is also a further in-depth understanding of the characteristics of the JavaScript language.

JavaScript function syntax

A function is a block of code wrapped in curly braces, preceded by the keyword function:

function functionname()
{
Here is the code to execute
}

When this function is called, the code within the function will be executed.

Functions can be called directly when an event occurs (such as when the user clicks a button) and can be called from anywhere by JavaScript.

Tip: JavaScript is case-sensitive. The keyword function must be lowercase, and the function must be called with the same case as the function name.

( function(){…} )() and ( function (){…} () ) are two common ways of writing JavaScript functions to execute functions immediately;

At first I thought it was an anonymous function wrapped in parentheses, and then a parentheses were added at the end to call the function. Finally, the purpose of executing the function immediately after it was defined was achieved;
It was later discovered that the reason for the parentheses was not that. To understand the immediate execution of functions, you need to first understand some basic concepts of functions.

Function declaration, function expression, anonymous function

Function declaration: function fnName () {…}; Use the function keyword to declare a function, and then specify a function name, which is called a function declaration.

Function expression: var fnName = function () {…}; Use the function keyword to declare a function, but do not give the function a name. Finally, assign the anonymous function to a variable, called a function expression. This is the most common function. Expression syntax form.

Anonymous function: function () {}; Use the function keyword to declare a function, but do not give the function a name, so it is called an anonymous function. Anonymous functions belong to function expressions. Anonymous functions have many functions. When assigned to a variable, a function is created , assigning an event becomes an event handler or creates a closure, etc.

The difference between function declaration and function expression:

1. When the Javascript engine parses the JavaScript code, it will "Function declaration Hoisting" the function declaration on the current execution environment (scope), and the function expression must wait until the Javascirtp engine executes the line where it is located. Only then will the function expression be parsed line by line from top to bottom;

2. You can add parentheses after the function expression to call the function immediately. Function declaration is not allowed and can only be called in the form of fnName().

Example:

 fnName(); 
 function fnName(){ 
  ... 
 } 
 //正常,因为"提升"了函数声明,函数调用可在函数声明之前 
 fnName(); 
 var fnName = function(){ 
  ... 
 } //报错,变量fnName还未保存对函数的引用,函数调用必须在函数表达式之后
 var fnName = function(){ 
  alert("Hello World"); 
 }(); 
 //函数表达式后面加括号,当javascript引擎解析到此处时能立即调用函数 
 function fnName(){ 
  alert("Hello World"); 
 }(); 
 //不会报错,但是javascript引擎只解析函数声明,忽略后面的括号,函数声明不会被调用 
 function(){ 
  console.log("Hello World"); 
 }();
 //语法错误,虽然匿名函数属于函数表达式,但是未进行赋值操作, 
//所以javascript引擎将开头的function关键字当做函数声明,

Error: A function name is required

After understanding some basic concepts of functions, let’s look back at ( function(){…} )() and ( function (){…} () ) two ways of writing functions that execute immediately,

At first I thought it was an anonymous function wrapped in parentheses, followed by a parentheses to call the function immediately. I didn’t know why the parentheses were added at the time;

I later understood that if you want to add parentheses after the function body to call it immediately, the function must be a function expression, not a function declaration.

 ( function(a){ 
  console.log(a); //firebug输出123,使用()运算符 
 })(123); 
 ( function(a){ 
  console.log(a); //firebug输出1234,使用()运算符 
 }(1234)); 
 ! function(a){ 
  console.log(a); //firebug输出12345,使用!运算符 
 }(12345); 
 + function(a){ 
  console.log(a); //firebug输出123456,使用+运算符 
 }(123456); 
 - function(a){ 
  console.log(a); //firebug输出1234567,使用-运算符 
 }(1234567); 
 var fn= function(a){ 
  console.log(a); //firebug输出12345678,使用=运算符 
 }(12345678)

To see the output, add it in front of function! , , - or even commas can have the effect of executing the function immediately after it is defined, and (),! Operators such as , , - and = all convert function declarations into function expressions, eliminating the ambiguity between the JavaScript engine in identifying function expressions and function declarations, and telling the JavaScript engine that this is a function expression, not a function declaration, and can be used later. Add parentheses and execute the function's code immediately.

Adding brackets is the safest way, because! Operators such as , , - will also perform operations with the return value of the function, sometimes causing unnecessary trouble.

But what is the use of writing like this?

There is no concept of private scope in JavaScript. If a project is developed by multiple people and some variables are declared in the global or local scope, they may be overwritten by other people accidentally using variables with the same name.

According to the characteristics of JavaScript function scope chain, you can use this technology to imitate a private scope and use anonymous functions as a "container". External variables can be accessed inside the "container", but the external environment cannot access the "container" "Internal variables, so variables defined inside (function(){...})() will not conflict with external variables, commonly known as "anonymous wrapper" or "namespace".

JQuery uses this method, wrapping the JQuery code in (function (window, undefined){...jquery code...} (window), when calling the JQuery code in the global scope, you can protect JQuery internal variables

The above content is the javascript immediate execution function introduced by the editor to you. I hope you like it.

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
JavaScript函数异步编程:处理复杂任务的必备技巧JavaScript函数异步编程:处理复杂任务的必备技巧Nov 18, 2023 am 10:06 AM

JavaScript函数异步编程:处理复杂任务的必备技巧引言:在现代前端开发中,处理复杂任务已经成为了必不可少的一部分。而JavaScript函数异步编程技巧则是解决这些复杂任务的关键。本文将介绍JavaScript函数异步编程的基本概念和常用的实践方法,并提供具体的代码示例,帮助读者更好地理解和使用这些技巧。一、异步编程的基本概念在传统的同步编程中,代码按

使用JavaScript函数实现网页导航和路由使用JavaScript函数实现网页导航和路由Nov 04, 2023 am 09:46 AM

在现代Web应用程序中,实现网页导航和路由是十分重要的一环。利用JavaScript的函数来实现这个功能,可以使我们的Web应用程序更加灵活、可扩展和用户友好。本文将介绍如何使用JavaScript函数来实现网页导航和路由,并提供具体的代码示例。实现网页导航对于一个Web应用程序而言,网页导航是用户操作最频繁的一个部分。当用户点击页面上的

使用JavaScript函数实现数据可视化的实时更新使用JavaScript函数实现数据可视化的实时更新Nov 04, 2023 pm 03:30 PM

使用JavaScript函数实现数据可视化的实时更新随着数据科学和人工智能的发展,数据可视化已经成为了一种重要的数据分析和展示工具。通过可视化数据,我们可以更直观地理解数据之间的关系和趋势。在Web开发中,JavaScript是一种常用的脚本语言,具备强大的数据处理和动态交互功能。本文将介绍如何使用JavaScript函数实现数据可视化的实时更新,并展示具体

使用JavaScript函数实现用户登录和权限验证使用JavaScript函数实现用户登录和权限验证Nov 04, 2023 am 10:10 AM

使用JavaScript函数实现用户登录和权限验证随着互联网的发展,用户登录和权限验证成为了很多网站和应用程序的必备功能。为了保护用户的数据安全和访问权限,我们需要使用一些技术和方法来验证用户的身份,并限制其访问的权限。JavaScript作为一种广泛使用的脚本语言,在前端开发中扮演着重要的角色。我们可以利用JavaScript函数来实现用户登录和权限验证功

使用JavaScript函数实现图片轮播和幻灯片效果使用JavaScript函数实现图片轮播和幻灯片效果Nov 04, 2023 am 08:59 AM

JavaScript是一种脚本语言,可以用来为网页添加交互效果。其中,图片轮播和幻灯片效果是常见的网页动画效果,本文将介绍如何使用JavaScript函数实现这两种效果,并提供具体代码示例。图片轮播图片轮播是一种将多张图片按照一定的方式轮流播放的效果。在实现图片轮播时,需要用到JavaScript的定时器和CSS样式控制。(1)准备工作首先,在HTML文件中

使用JavaScript函数实现用户交互和动态效果使用JavaScript函数实现用户交互和动态效果Nov 03, 2023 pm 07:02 PM

使用JavaScript函数实现用户交互和动态效果随着现代网页设计的发展,用户交互和动态效果成为了吸引用户眼球的关键。JavaScript作为一种常用的脚本语言,拥有强大的功能和灵活的特性,能够实现各种各样的用户交互和动态效果。本文将介绍一些常见的JavaScript函数,并给出具体的代码示例。改变元素样式(style)通过JavaScript函数能够轻松改

使用JavaScript函数实现数据可视化的动态更新使用JavaScript函数实现数据可视化的动态更新Nov 03, 2023 pm 04:56 PM

使用JavaScript函数实现数据可视化的动态更新数据可视化是大数据时代中非常重要的一环,它能够以直观的方式展示数据,帮助人们更好地理解和分析数据。而JavaScript作为一种客户端的脚本语言,能够通过函数的方式来实现数据可视化的动态更新。本文将介绍如何使用JavaScript函数来实现这一功能,并提供具体的代码示例。一、数据可视化基础在开始编写代码之前

使用JavaScript函数实现文件上传和下载使用JavaScript函数实现文件上传和下载Nov 04, 2023 am 08:30 AM

使用JavaScript函数实现文件上传和下载随着互联网的发展和普及,文件上传和下载成为了网页应用中常见的功能之一。本文将介绍如何使用JavaScript函数来实现文件上传和下载的功能,并提供具体的代码示例。文件上传文件上传指的是将本地的文件通过网页上传到服务器。HTML5中提供了FileAPI用于处理文件的选择和上传。我们可以利用FileAPI中的Fi

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version