search
HomeWeb Front-endJS TutorialA brief analysis of function declarations and function expressions - declaration of function declarations in advance_Basic knowledge

The first two days of the class party, apart from eating, drinking, having fun, sleeping and talking, it was very joyful. It’s really not as good as having fun alone than having fun together.

PS: Those who have graduated or are about to graduate, just get together if you have time. After graduation, there will be too little time for you to get together.

Now I have some time to look at some things and summarize some things, and because I looked at the function part of JavaScript piece by piece some time ago, I took the time to summarize the relevant parts of the function. Of course, some parts are my own. I understand. If there is anything wrong with your understanding, please feel free to point it out.

In this section, I will talk about the declaration of function declarations in advance based on my own understanding.

Note: In some places, it is also called function declaration promotion. The translation is different, but the meaning is the same, as long as everyone understands it. Long live understanding!

Before talking about the declaration of function declaration in advance, it is necessary to introduce several methods of function definition, which should be familiar to most friends. If you know something or don’t want to know it, just roll it down. If you’re not familiar with it or want to get familiar with it, just slow down and start walking.

How to define functions

There are three main ways to define functions:

1. Function Declaration
2. Function Expression)
3.new Function constructor
Among them, the function definition methods of function declaration and function expression are often used. These two methods have very subtle differences and connections, and the use of these two methods is also easy to confuse, so this article mainly summarizes these two methods. Relevant knowledge points about function definition methods. Of course, the theme of this article is still about functions in advance.

Typical format of function declaration:

function functionName(arg1, arg2, ...){
  <!-- function body -->
}

Function expression

•Typical format of function expression:

var variable=function(arg1, arg2, ...){
      <!-- function body -->
}

Function expression containing name (brackets, function name):

var variable=function functionName(arg1, arg2, ...){
    <!-- function body -->
}

Function expressions with names like the above can be used recursively:

var variable=function functionName(x){
    if(x<=1)
      return 1;
    else
      return x*functionName(x);
}

Declaration in advance

var declaration in advance

Everyone should have heard of the statement of declaration in advance. I would like to reiterate it here because declaration in advance is an important difference between function declaration and function expression. It is important for us to further understand these two function definition methods. important meaning.

But before talking about the function declaration in advance, it is necessary to talk about the var declaration in advance.

First give the conclusion in advance of the var statement:

Variables are defined in the script or function in which they are declared, and the variable declaration statement will be advanced to the top of the script or function. However, the variable initialization operation is still performed at the location of the original var statement, and the value of the variable is undefined before the declaration statement.

Three simple points can be summarized from the above conclusion:

1. Variable declaration will be advanced to the top of the function;
2. Only the declaration is advanced, the initialization is not advanced, and the initialization is still performed at the original initialization position;
3. The value of the variable before declaration is undefined.

Let’s give an example:

var handsome='handsome';
function handsomeToUgly(){
  alert(handsome);
  var handsome='ugly';
  alert(handsome);
}
handsomeToUgly();

The correct output is:
First output undefined, then output ugly.

The wrong output is:
First output handsome, then output ugly.

Here is the role of variable declaration in advance. The handsome local variable is defined in the entire function body. The handsome variable in the function body is suppressed. Oh no, it covers the handsome global variable with the same name. Because the variable is declared in advance, that is, var handsome is advanced to the function. At the top, this is what it looks like:

var handsome='handsome';
function handsomeToUgly(){
  var handsome;
  alert(handsome);
  var handsome='ugly';
  alert(handsome);
}
handsomeToUgly();

So before alert(handsome), there is already a var handsome statement, as mentioned above

The value of the variable before declaration is undefined
So the first output is undefined.

And because of the above mentioned:

Only the declaration is advanced, the initialization is not advanced, and the initialization is still performed at the original initialization position
So the second output is ugly.

Function declaration in advance
In the next two chapters, we will start talking about the declaration of function declarations in advance in conjunction with the var declaration.

Everyone should be familiar with the declaration of function declaration in advance. Let me give you a very familiar example.

sayTruth();<!-- 函数声明 -->
function sayTruth(){
  alert('myvin is handsome.');
}

sayTruth();<!-- 函数表达式 -->
var sayTruth=function(){
  alert('myvin is handsome.');
}

小伙伴们都知道,对于函数声明的函数定义方法,即上面的第一种函数调用方法是正确的,可以输出myvin is handsome.的真理,因为函数调用语句可以放在函数声明之后。而对于函数表达式的函数定义方法,即上面的第二种函数调用的方法是不能输出myvin is handsome.的正确结果的。

结合上面的myvin is handsome.例子,函数声明提前的结论似乎很好理解,不就是在使用函数声明的函数定义方法的时候,函数调用可以放在任意位置嘛。对啊,你说的很对啊,小伙伴,我都不知道怎么反驳你了。那就容我再扯几句。

从小伙伴所说的

不就是在使用函数声明的函数定义方法的时候,函数调用可以放在任意位置嘛
可以引出一点:

函数声明提前的时候,函数声明和函数体均提前了。

而且:

函数声明是在预执行期执行的,就是说函数声明是在浏览器准备执行代码的时候执行的。因为函数声明在预执行期被执行,所以到了执行期,函数声明就不再执行(人家都执行过了自然就不再执行了)。

上面是一点。

函数表达式为什么不能声明提前
我们再说一点:为什么函数表达式不能像函数声明那样进行函数声明提前呢?

辛亏我知道一点儿,否则真不知道我该怎么回答呢?

咳咳,按照我的理解给小伙伴们解释一下下:

我们上面说了var的声明提前,注意我上面提过的:

只是声明被提前,初始化不提前,初始化还在原来初始化的位置进行初始化

Ok,我们把函数表达式摆在这看看:

var variable=function(arg1, arg2, ...){
          <!-- function body -->
}

函数表达式就是把函数定义的方式写成表达式的方式(貌似是白说,但是这对于解释和理解为毛函数表达式不能函数声明提前具有良好的疗效),就是把一个函数对象赋值给一个变量,所以我们把函数表达式写成这个样子:

var varible=5看到这,也许小伙伴们会明白了,一个是把一个值赋值给一个变量,一个是把函数对象赋值给一个变量,所以对于函数表达式,变量赋值是不会提前的,即function(arg1, arg2, ...){}是不会提前的,所以函数定义并没有被执行,所以函数表达式不能像函数声明那样进行函数声明提前。

函数声明提前的实例分析

还是那句话,还是例子来的实在:

sayTruth();
if(1){
  function sayTruth(){alert('myvin is handsome')};
}
else{
  function sayTruth(){alert('myvin is ugly')};
}

在浏览器不抛出错误的情况下(请自行测试相应的浏览器是否有抛出错误的情况,为啥我不测试?我能说我懒么。。。),浏览器的输出结果是输出myvin is ugly(我不愿承认,但是事实就是这样啊啊啊啊,难道道出了人丑就该多读书??????)。

为什么呢?当然是声明提前了。因为函数声明提前,所以函数声明会在代码执行前进行解析,执行顺序是这样的,先解析function sayTruth(){alert('myvin is handsome')},在解析function sayTruth(){alert('myvin is ugly')},覆盖了前面的函数声明,当我们调用sayTruth()函数的时候,也就是到了代码执行期间,声明会被忽略,所以自然会输出myvin is ugly(好残酷的现实。。。)。忘了的可以看上面说过的:

函数声明是在预执行期执行的,就是说函数声明是在浏览器准备执行代码的时候执行的。因为函数声明在预执行期被执行,所以到了执行期,函数声明就不再执行了(人家都执行过了自然就不再执行了)。

小了个结

关于函数声明的函数提前(提升)就聊到这里先,希望我的理解和扯淡能够对有需要的小伙伴有所帮助。

当然,实践出真知。对事物的了解、认知和运用还是在于多看多用多总结,记得有句名言,是讲声明和实践的:“动起来,为新的声明喝彩。”。

以上这篇浅析函数声明和函数表达式——函数声明的声明提前就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version