search
HomeWeb Front-endJS TutorialDeep understanding of functions in JavaScript

Function is the basis for modular programming. To write complex Ajax applications, you must have a deeper understanding of functions. Functions in JavaScript are different from other languages. Each function is maintained and run as an object. Through the properties of function objects, you can easily assign a function to a variable or pass the function as a parameter. Before continuing, let’s take a look at the syntax of using functions:

function func1(…){…}
var func2=function(…){…};
var func3=function func4(…){…};
var func5=new Function();
 These are the correct syntax for declaring functions. They are very different from common functions in other languages ​​or the function definition methods introduced before. So why can it be written like this in JavaScript? What is the syntax it follows? These are described below.

 Understanding Function Object

  You can use the function keyword to define a function, specify a function name for each function, and call it through the function name. When JavaScript is interpreted and executed, functions are maintained as an object, which is the Function Object to be introduced.

  Function objects are essentially different from other user-defined objects. This type of object is called an internal object. For example, date object (Date), array object (Array), and string object (String) are all internal objects. . The constructors of these built-in objects are defined by JavaScript itself: by executing a statement such as new Array() to return an object, JavaScript has an internal mechanism to initialize the returned object, instead of the user specifying how the object is constructed.

 In JavaScript, the corresponding type of function object is Function, just like the corresponding type of array object is Array, and the corresponding type of date object is Date. You can create a function object through new Function(), or you can use the function keyword to create an object. For ease of understanding, we compare the creation of function objects with the creation of array objects. Let’s look at the array object first: The following two lines of code both create an array object myArray:

var myArray=[];
//Equivalent to
var myArray=new Array();
Similarly, the following two pieces of code also Is to create a function myFunction:
function myFunction(a,b){
       return a+b;
}
//Equivalent to
var myFunction=new Function("a","b","return a+b" );
By comparing it with the statement to construct an array object, you can clearly see the essence of the function object. The function declaration introduced earlier is the first way of the above code, and inside the interpreter, when this syntax is encountered, A Function object will be automatically constructed to store and run the function as an internal object. It can also be seen from here that a function object name (function variable) and an ordinary variable name have the same specifications. Both can refer to the variable through the variable name, but the function variable name can be followed by parentheses and a parameter list to perform the function. transfer.

  It is not common to create a function in the form of new Function(), because a function body usually has multiple statements. If they are passed as parameters in the form of a string, the readability of the code will be poor. The following is an introduction to its usage syntax:

var funcName=new Function(p1, p2,, pn, body);
The types of parameters are all strings. p1 to pn represent the parameter name list of the created function, and body represents the created function. The function body statement of the function, funcName is the name of the created function. You can create an empty function without specifying any parameters, and create an unnamed function without specifying funcName. Of course, such a function has no meaning.

 It should be noted that p1 to pn are lists of parameter names, that is, p1 can not only represent a parameter, it can also be a comma-separated parameter list. For example, the following definition is equivalent:

new Function( "a", "b", "c", "return a+b+c")
new Function("a, b, c", "return a+b+c")
new Function("a,b ", "c", "return a+b+c")
 JavaScript introduces the Function type and provides syntax such as new Function() because function objects must use the Function type to add properties and methods.
The essence of a function is an internal object, and the JavaScript interpreter determines how it operates. The function created by the above code can be called using the function name in the program. The function definition issues listed at the beginning of this section are also explained. Note that you can directly add the parentheses behind the function declaration to indicate that the function calls immediately after the creation is completed, for example:

var I = Function (a, b) (i);
This code will display that the value of variable i is equal to 3. i represents the returned value, not the created function, because the brackets "(" have a higher priority than the equal sign "=". Such code may not be commonly used, but when the user wants to This is a good solution for modular design or to avoid naming conflicts.

It should be noted that although the following two methods of creating functions are equivalent:

function funcName(){
                                                                                        Function body
                                 // Function body Create an unnamed function, just let a variable point to the unnamed function. There is only one difference in usage: for a named function, it can be defined after it is called; while for an unnamed function, it must be defined before it is called. For example:

<script language="JavaScript" type="text/javascript">
<!--
func();
var func=function(){

      alert(1)

}
//-- >
</script>
This statement will generate an undefined error for func, and:

<script language="JavaScript" type="text/javascript">
<!--
func();
function func( ; >

<!--

func();
var someFunc=function func(){
    alert(1)
}
//-->
</script>

  It can be seen that although JavaScript is an explanation type language, but it will check whether there is a corresponding function definition in the entire code when the function is called. This function name will only be valid if it is defined in the form of function funcName(), and cannot be an anonymous function.

 The relationship between function objects and other internal objects


 In addition to function objects, there are many internal objects, such as: Object, Array, Date, RegExp, Math, Error. These names actually represent a type, and an object can be returned through the new operator. However, function objects are different from other objects. When typeof is used to get the type of a function object, it will still return the string "function", and when typeof an array object or other object, it will return the string "object". The following code illustrates the different types of typeof:



alert(typeof(Function)));
alert(typeof(new Function()));
alert(typeof(Array));

alert(typeof( Object));

alert(typeof(new Array()));

alert(typeof(new Date()));

alert(typeof(new Object()));

Running this code you can find: previous 4 Each statement will display "function", while the next three statements will display "object". It can be seen that a new function actually returns a function. This is very different from other objects. Other types such as Array and Object will return a normal object through the new operator. Although the function itself is also an object, it is still different from ordinary objects because it is also an object constructor. That is to say, you can create a new function to return an object, which has been introduced before. All objects whose typeof returns "function" are function objects. Such objects are also called constructors. Therefore, all constructors are objects, but not all objects are constructors.

Since the function itself is also an object, their type is function. Thinking of the class definitions of object-oriented languages ​​​​such as C++ and Java, you can guess the role of the Function type, that is, you can define some methods and attributes for the function object itself. With the help of the prototype object of the function, the definition of the Function type can be easily modified and expanded. For example, the function type Function is extended below and the method1 method is added to it. The function is to pop up a dialog box to display "function":

Function.prototype. method1=function(){

alert("function");
}
function func1(a,b,c){
return a+b+c;
}
func1.method1();
func1.method1.method1 ();
Pay attention to the last statement: func1.method1.mehotd1(), which calls the method1 method of the function object method1. Although it seems a bit confusing, a closer look at the syntax makes it clear: this is a recursive definition. Because method1 itself is also a function, it also has the properties and methods of the function object. All method extensions to the Function type have such recursive properties.

 Function is the basis of all function objects, and Object is the basis of all objects (including function objects). In JavaScript, any object is an instance of Object. Therefore, the Object type can be modified so that all objects have some common properties and methods. Modifying the Object type is done through prototype:

Object.prototype.getType =function(){
                                                                                                                                                                                                                                                                =function(),

alert(func1.getType());
 The above code adds the getType method to all objects, which returns the type of the object. The two alert statements will display "object" and "function" respectively.

 Pass function as parameter

 The essence of function objects has been introduced before. Each function is represented as a special object, which can be easily assigned to a variable, and then the function is called through this variable name. As a variable, it can be passed to another function in the form of a parameter. This has been seen in the previous introduction to the JavaScript event handling mechanism. For example, the following program passes func1 as a parameter to func2:

function func1( theFunc){
   theFunc();
}
function func2(){
   alert("ok");
}
func1(func2);
  In the last statement, func2 is passed as an object to the formal parameter of func1 theFunc, and then theFunc is called internally by func1. In fact, passing functions as parameters or assigning functions to other variables is the basis of all event mechanisms.

 For example, if you need to perform some initialization work when the page is loading, you can first define an init initialization function, and then bind it to the page loading completion event through the window.onload=init; statement. The init here is a function object, which can be added to the window's onload event list.

The above is the in-depth understanding of functions in JavaScript. For more related articles, please pay attention to the PHP Chinese website (www.php.cn)!


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
Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

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.

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools