Home  >  Article  >  Web Front-end  >  Deep understanding of functions in JavaScript

Deep understanding of functions in JavaScript

黄舟
黄舟Original
2016-12-15 10:29:26739browse

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