


Various common function definition methods in JavaScript_javascript tips
This article details various common function definition methods in JavaScript and shares them with you for your reference. The specific analysis is as follows:
First, let’s take a look at the four most common function definitions in JavaScript:
The function defined using the Function constructor, the code is as follows:
var multiply = new Function('x', 'y', 'return x * y;');
Function declaration, this method is also the most common one:
function multiply(x, y) { return x * y; }
Function expression, declared as an anonymous function and then assigned to a variable, a very common way:
var multiply = function(x, y) { return x * y; }
Function expression, but the function is declared as a named function and then assigned to a variable. It looks exactly like the previous method:
var multiply = function multi(x, y) { return x * y; }
First, let’s compare the direct relationship between the function name and the function variable to which the function is assigned. It’s really confusing... To be more intuitive, let’s talk about it from Example 4 just now. It is the relationship between the function variable multiply and the function name multi. :
The function name cannot be modified. On the contrary, the function variable can be reassigned. It should be easy to understand that function variables can be reassigned. The multiply variable we just defined in our fourth example is not pleasing to the eye, so it can be reassigned as:
multiply = function(x, y) { return x + y; }
Immediately transformed from multiplication to addition. But it is impossible to change the function variable multi. The function definition is already there. As long as the reference to it is still retained, it will not change. Maybe it is not easy to understand here. Think about it like this first and read on. You should be able to understand it gradually.
The function name cannot be used outside the function. It is only visible inside the function body. A very simple example:
var foo = function bar() { alert('hello'); } foo(); // 提示“hello”字符串 bar(); // 执行报错,bar未定义
Obviously, bar here is indeed a function name, but it cannot be called externally. At this time, some children will definitely ask why this example still looks so good. It is the same as Example 4. Why not use the method of Example 2? Good question, let me break it down slowly.
Continuing with Example 4, we can see that the function name (multi) and the function variable (multiply) are not the same. In fact, they have no relationship at all, so there is no need to keep them consistent. Speaking of which, I think the above four examples can be reduced to three. Examples 2 and 4 should be essentially the same. What, don’t believe it? Hee hee, I have to continue to tell the truth~keep reading~~
We found that compared with Example 4, Example 2 only lacks the function variable of var, and compared with Example 4, Example 3 only lacks the function name. From the perspective of the phenomenon, Example 2 and Example 4 The essence is the same, the ironclad proof is as follows:
function foo() {} alert(foo); // 提示包含“foo”的函数名 var bar = foo; alert(bar); // 提示依然只包含“foo”的函数名,和bar半毛钱关系都没有
Is it indeed irrefutable evidence? Can the code similar to Example 2 above be combined and written in the same way as Example 4? Correct, this is what I just said. The essence of the two should be the same. It’s just that when defining the function in use case 2, the JS engine did some things for us, such as declaring a function named multiply, and also quietly defined a function called multiply. Call the variable multiply, and then assign it to this variable. The two names are exactly the same. When we think that when we use the function name multiply, we are actually using the function variable multiply. I am confused~ To be honest, I am also confused~ ~In short, when we call, we actually use function variables to call, and the function name cannot be used to call the function externally, so I have the above inference.
But there is a small difference to be mentioned here. The difference between functions defined in function declaration mode and constructor declaration or function expression declaration is that functions in function declaration mode can be called before the function is defined. ...I won’t talk anymore, let’s look at the code:
foo(); // 提示Foo function foo() { alert('Foo'); } bar(); // 哥们,和上面确实不一样,就不要逞能,这不报错了?提示bar未定义 var bar = function() { alert('Bar'); }
Let’s talk about the function declared by the constructor. The function declared in this way will not inherit the scope of the current declaration position. It will only have the global scope by default. However, this is also available in several other function declaration methods, as follows :
function foo() { var hi = 'hello'; //return function() { // alert(hi); //}; return Function('return hi;'); } foo()(); // 执行效果大家自己跑一下看看
可以想见,用构造函数声明返回的这个函数执行必然报错,因为其作用域(即全局作用域)中没有hi这个变量。
还有一点,就是往往大家要说构造函数方式声明的函数效率要低,这是为什么呢?今天从文档是得知是因为另外3种方式申明的函数只会被解析一次,其实他们存在于闭包中,但是那也只与作用域链有关,函数体是只会被解析一次的。但是构造函数方式呢,每次执行函数的时候,其函数体都会被解析一次,我们可以想想这样声明的函数是一个对象,其中存放了参数以及函数体,每次执行的时候都要先解析一次,参数和函数体,才会执行,这样必然效率低下。具体实验不知道如何做?
最后说一个大家都不怎么注意的地方,什么时候看似函数声明方式的方式却不是函数生命方式(还是这么绕~简单点儿说,就是例2的方式什么时候在不经意间就成其他方式了):
当成为表达式的一部分,就如同例3和例4。
不再是脚本本身或者函数的“源元素”(source element)。什么是源元素呢?即在脚本中的非嵌套语句或者函数体(A "source element" is a non-nested statement in the script or a function body),例如:
var x = 0; // source element if (x == 0) { // source element x = 10; // not a source element, 因为嵌套在了if语句里 function boo() {} // not a source element, 因为嵌套在了if语句里 } function foo() { // source element var y = 20; // source element function bar() {} // source element while (y == 10) { // source element function blah() {} // not a source element, 因为嵌套在了while语句里 y++; // not a source element, 因为嵌套在了while语句里 } }
源元素的概念大概有了理解,继续刚刚说的函数声明,请看:
// 函数声明 function foo() {} // 函数表达式 (function bar() {}) // 函数表达式 x = function hello() {} if (x) { // 函数表达式 function world() {} } // function statement function a() { // function statement function b() {} if (0) { // 函数表达式 function c() {} } }
最后这里说一下我自己的理解,之所以要区分函数声明与非函数声明,因为在我看了,函数声明方式的函数定义,在JS解析引擎执行的时候会将其提前声明,也就是像我们刚刚上面说的那样,可以在函数定义之前使用,实际上是解析引擎在我们使用前已经将其解析了,但是非函数声明式,就像表达式函数声明,JS解析引擎只会把var声明的变量提前定义,此时变量值为undefined,而真正对这个变量的赋值是在代码实际所在位置,因此上述提到报错都是undefined,实际变量已经定义了,只是还没有赋值,JS解析引擎不知道它为函数。
相信本文所述对大家javascript WEB程序设计的有一定的借鉴价值。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

Go language provides two dynamic function creation technologies: closure and reflection. closures allow access to variables within the closure scope, and reflection can create new functions using the FuncOf function. These technologies are useful in customizing HTTP routers, implementing highly customizable systems, and building pluggable components.

In C++ function naming, it is crucial to consider parameter order to improve readability, reduce errors, and facilitate refactoring. Common parameter order conventions include: action-object, object-action, semantic meaning, and standard library compliance. The optimal order depends on the purpose of the function, parameter types, potential confusion, and language conventions.

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

The key to writing efficient and maintainable Java functions is: keep it simple. Use meaningful naming. Handle special situations. Use appropriate visibility.

The advantages of default parameters in C++ functions include simplifying calls, enhancing readability, and avoiding errors. The disadvantages are limited flexibility and naming restrictions. Advantages of variadic parameters include unlimited flexibility and dynamic binding. Disadvantages include greater complexity, implicit type conversions, and difficulty in debugging.
