Functions are the basis for modular programming. When writing complex Ajax applications, you must have a deeper understanding of functions.
Functions in javascript are different from other languages, and each function is maintained and run as an object. Through the properties of the function object, it is very convenient to assign a function to a variable or pass a function as a parameter. Before continuing, let’s take a look at the syntax of the function:
The following is a quoted snippet:
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 the functions commonly found in other languages or the previously introduced function definition methods. So why can I write this in JavaScript? What is the syntax it follows? These are described below.
Know Function Object
You can use the function keyword to define a function, and specify a function name for each function, and call it through the function name. When JavaScript is interpreted and executed, functions are maintained as one object, which is the function object to be introduced.
Function objects are essentially different from objects defined by other users. This type of object is called internal objects. For example, date objects, array objects, and string objects are all internal objects. The constructors of these built-in objects are defined by JavaScript itself: by executing a statement like new Array() to return an object. JavaScript has a mechanism inside to initialize the returned object, rather than specifying the object's construction method by the user.
In JavaScript, the corresponding type of function object is Function, just as 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 create an object through function keyword. 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 create an array object myArray:
The following is a quoted snippet:
var myArray=[];
//Equivalent to
var myArray=new Array();
Similarly, the following two pieces of code also create a function myFunction:
function myFunction(a,b){
return a+b;
}
//Equivalent to
var myFunction=new Function("a","b","return a+b");
By comparing with the statements that construct array object, you can clearly see the essence of the function object. The function declaration introduced above is the first way of the above code. In the interpreter, when encountering this syntax, a Function object will be automatically constructed and the function will be stored and run as an internal object. From here, we can also see that a function object name (function variable) and a normal variable name have the same specification. This variable can be referenced by the variable name, but the function variable name can be followed by brackets and parameter lists to make function calls.
It is not common to create a function in the form of new Function(), because a function body usually has multiple statements, and if they are passed as a string as a parameter, the code is poorly readable. The following is a syntax of its use:
The following is a quoted snippet:
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, body represents the function body statement of the created function, and 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 is a list 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:
The following is a quoted snippet:
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, which is determined by the JavaScript interpreter. The functions created through the above code can be called in the program using the function name. The function definition problem listed at the beginning of this section is also explained. Note that you can directly add brackets to the function declaration to indicate that the function call is immediately after the creation is completed, for example:
The following is a quoted snippet:
var i=function (a,b){
return a+b;
}(1,2);
alert(i);
This code will show that the value of variable i is equal to 3. i represents the returned value, not the created function, because the bracket "(" has a higher priority than the equal sign "=". Such code may not be commonly used, but this is a good solution when users want to modularize design in long code segments or want to avoid naming conflicts.
It should be noted that although the following two methods of creating functions are equivalent:
The following is a quoted snippet:
function funcName(){
//Function body
}
//Equivalent to
var funcName=function(){
//Function body
}
But the first method creates a named function, and the next method creates an unnamed function, just letting a variable point to the unnamed function. There is only one difference in use: for a named function, it can appear after the call and then be defined; for a named function, it must be defined before the call. For example:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
var func=function(){
alert(1)
}
//-->
</script>
This statement will produce a func undefined error, while:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
function func(){
alert(1)
}
//-->
</script>
It can be executed correctly, and the following statements can also be executed correctly:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
var someFunc=function func(){
alert(1)
}
//-->
</script>
It can be seen that although JavaScript is an interpreted language, it checks whether there is a corresponding function definition in the entire code when calling a function. 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, and Error. These names actually represent a type and can be returned with an object through the new operator. However, function objects are different from other objects. When using typeof 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 examples the different types of typeof:
The following is a quoted snippet:
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 shows that the first 4 statements will display "function", while the next 3 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 Array, Object, etc. will return a normal object through the new operator. Although a function itself is an object, it is still different from an ordinary object because it is also an object constructor. That is to say, you can new a function to return an object, which has been introduced before. All objects that return "function" in typeof are function objects. Such objects are also called constructors, so all constructors are objects, but not all objects are constructors.
Since functions themselves are objects, their type is function, and when they are associated with object-oriented language definitions such as C++ and Java, you can guess the role of Function types, that is, you can define some methods and properties for the function object itself. With the help of the function prototype object, the definition of Function type can be easily modified and expanded. For example, the function type Function is expanded below and the method1 method is added to it. The function is to pop up the dialog box to display "function":
The following is a quoted snippet:
.method1=function(){
alert("function");
}
function func1(a,b,c){
return a+b+c;
}
func1.method1();
func1.method1.method1();
Note the last statement: func1.method1.mehotd1(), which calls the method1 method of the function object method1. Although it seems a bit confusing, it is still clear to look at the syntax after a closer look: 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 expansions of Function type have such recursive properties.
Function is the basis of all function objects, while Object is the basis of all objects (including function objects). In JavaScript, any object is an instance of Object. Therefore, you can modify the Object type to make all objects have some common properties and methods. Modifying the Object type is done through prototype:
The following is a quoted snippet:
=function(){
return typeof(this);
}
var array1=new Array();
function func1(a,b){
return a+b;
}
alert(());
alert(());
The above code adds a getType method to all objects, which is used to return the type of the object. The two alert statements will display "object" and "function" respectively.
Pass the function as a parameter
The nature of function objects has been introduced earlier. Each function is represented as a special object. It can be easily assigned to a variable and then function calls are made through this variable name. As a variable, it can be passed to another function as a parameter. This has been seen in the JavaScript event handling mechanism mentioned earlier. For example, the following program passes func1 as a parameter to func2:
The following is a quoted snippet:
function func1(theFunc){
theFunc();
}
function func2(){
alert("ok");
}
func1(func2);
In the last statement, func2 is passed as an object to func1's formal parameter theFunc, and then theFunc is called internally by func1. In fact, passing a function as a parameter, or assigning a function to other variables is the basis of all event mechanisms.
For example, if you need to do some initialization work when the page is loaded, you can first define an init initialization function, and then bind it to the event that the page is loaded through the =init; statement. The init here is a function object that can be added to the onload event list of window.
Implicit parameters passed to the function: arguments
When making a function call, in addition to the specified parameters, an implicit object is created - arguments. arguments is an object similar to an array but not an array. It is said that it is similar because it has the same access properties as an array. You can use syntax such as arguments[index] to get the value and have the array length attribute length property. The arguments object stores the parameters actually passed to the function, and is not limited to the parameter list defined by the function declaration, for example:
The following is a quoted snippet:
function func(a,b){
alert(a);
alert(b);
for(var i=0;i<;i++){
alert(arguments[i]);
}
}
func(1,2,3);
When the code is run, it will be displayed in sequence: 1, 2, 1, 2, 3. Therefore, when defining a function, even if the parameter list is not specified, the obtained parameters can still be referenced through arguments, which brings great flexibility to programming. Another property of the arguments object is callee, which represents a reference to the function object itself, which is conducive to the recursion of anonymous functions or to ensure the encapsulation of the function. For example, using recursion to calculate the sum of natural numbers from 1 to n:
The following is a quoted snippet:
var sum=function(n){
if(1==n)return 1;
else return n+sum(n-1);
}
alert(sum(100));
The function contains calls to sum itself. However, for JavaScript, the function name is just a variable name. Calling sum inside the function is equivalent to calling a global variable. It cannot be well reflected that it is calling itself, so using attributes is a better way:
The following is a quoted snippet:
var sum=function(n){
if(1==n)return 1;
else return n+(n-1);
}
alert(sum(100));
The callee attribute is not the only feature of arguments that differ from array objects. The following code shows that arguments are not created by the Array type:
The following is a quoted snippet:
.p1=1;
alert(new Array().p1);
function func(){
alert(arguments.p1);
}
func();
Running the code can find that the first alert statement is displayed as 1, which means that the array object has attribute p1, while the func call is displayed as "undefined", that is, p1 is not an attribute of arguments. It can be seen that arguments are not an array object.
The apply, call method and length attribute of the function
JavaScript defines two methods for function objects: apply and call. Their functions are to bind the function to another object to run. The two are only different in the way of defining parameters:
The following is a quoted snippet:
(thisArg,argArray);
(thisArg[,arg1[,arg2…]]);
From the function prototype, we can see that the first parameter is named thisArg, that is, this pointer inside all functions will be assigned to thisArg, which achieves the purpose of running the function as a method of another object. In addition to thisArg parameter, both methods are parameters passed for Function objects. The following code illustrates how apply and call methods work:
The following is a quoted snippet:
//Define a function func1, with attribute p and method A
function func1(){
="func1-";
=function(arg){
alert(+arg);
}
}
//Define a function func2, with attribute p and method B
function func2(){
="func2-";
=function(arg){
alert(+arg);
}
}
var obj1=new func1();
var obj2=new func2();
("byA"); //Show func1-byA
("byB"); //Show func2-byB
(obj2,["byA"]); //Show func2-byA, where ["byA"] is an array with only one element, the same below
(obj1,["byB"]); //Show func1-byB
(obj2,"byA"); //Show func2-byA
(obj1,"byB"); //Show func1-byB
It can be seen that after obj1's method A is bound to obj2 and run, the entire running environment of function A is transferred to obj2, that is, this pointer points to obj2. Similarly, function B of obj2 can also be bound to obj1 object to run. The last 4 lines of the code show the difference between the apply and call function parameter forms.
Unlike the length attribute of arguments, the function object also has a property length, which represents the number of parameters specified when the function is defined, rather than the number of parameters actually passed when the call is called. For example, the following code will show 2:
The following is a quoted snippet:
function sum(a,b){
return a+b;
}
alert();
Deeply understand this pointer in JavaScript
This pointer is an important concept in object-oriented programming, which represents the currently running object. When implementing an object's method, you can use this pointer to obtain a reference to the object itself.
Unlike other object-oriented languages, this pointer in JavaScript is a dynamic variable. This pointer in a method does not always point to the object that defines the method. There have been examples like this when talking about the apply and call methods of the function in the previous section. For easy understanding, let’s take a look at the following example:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
//Create two empty objects
var obj1=new Object();
var obj2=new Object();
//Add attribute p to both objects and equal to 1 and 2 respectively
=1;
=2;
//Add a method to obj1 to display the value of p
=function(){
alert(); //On the surface this pointer points to obj1
}
//Calling the getP method of obj1
();
// Make obj2's getP method equal to obj1's getP method
=;
//Calling the getP method of obj2
();
//-->
</script>
Judging from the execution results of the code, the dialog box pops up to display 1 and 2 respectively. It can be seen that the getP function is defined only once, run on different occasions, and displays different run results, which is determined by the change of this pointer. In obj1's getP method, this points to the obj1 object, and in obj2's getP method, this points to the obj2 object, and references the attribute p that both objects have through this pointer.
It can be seen that this pointer in JavaScript is a dynamically changing variable that indicates the object currently running the function. By the nature of this pointer, you can better understand the nature of objects in JavaScript: an object is a collection of one or more properties (methods). Each set element can not only belong to one set, but can dynamically belong to multiple sets. In this way, the pointer points to whom a method (collection element) is called. In fact, the apply method and call method introduced above are implemented by forcibly changing the value of this pointer, so that this pointer points to the object specified by the parameter, so as to run the method of one object as another object.
The elements (i.e. attributes or methods) of each object collection are also an independent part. There is no difference between a global function and a function defined as an object method, because global functions and variables can be regarded as methods and properties of window objects. You can also use the new operator to operate an object's method to return an object, so that the method of an object can be defined as a class, where this pointer will point to the newly created object. As you can see later, object names can play a namespace role at this time, which is a skill for object-oriented programming using JavaScript. For example:
The following is a quoted snippet:
var namespace1=new Object();
namespace1.class1=function(){
//Initialize the object code
}
var obj1=new namespace1.class1();
Here you can regard namespace1 as a namespace.
Due to the dynamic change characteristics of object properties (methods), the reference between two properties (methods) of an object must be passed through this pointer, while in other languages, this keyword can be omitted. As in the example above:
The following is a quoted snippet:
=function(){
alert(); //On the surface this pointer points to obj1
Functions in javascript are different from other languages, and each function is maintained and run as an object. Through the properties of the function object, it is very convenient to assign a function to a variable or pass a function as a parameter. Before continuing, let’s take a look at the syntax of the function:
The following is a quoted snippet:
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 the functions commonly found in other languages or the previously introduced function definition methods. So why can I write this in JavaScript? What is the syntax it follows? These are described below.
Know Function Object
You can use the function keyword to define a function, and specify a function name for each function, and call it through the function name. When JavaScript is interpreted and executed, functions are maintained as one object, which is the function object to be introduced.
Function objects are essentially different from objects defined by other users. This type of object is called internal objects. For example, date objects, array objects, and string objects are all internal objects. The constructors of these built-in objects are defined by JavaScript itself: by executing a statement like new Array() to return an object. JavaScript has a mechanism inside to initialize the returned object, rather than specifying the object's construction method by the user.
In JavaScript, the corresponding type of function object is Function, just as 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 create an object through function keyword. 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 create an array object myArray:
The following is a quoted snippet:
var myArray=[];
//Equivalent to
var myArray=new Array();
Similarly, the following two pieces of code also create a function myFunction:
function myFunction(a,b){
return a+b;
}
//Equivalent to
var myFunction=new Function("a","b","return a+b");
By comparing with the statements that construct array object, you can clearly see the essence of the function object. The function declaration introduced above is the first way of the above code. In the interpreter, when encountering this syntax, a Function object will be automatically constructed and the function will be stored and run as an internal object. From here, we can also see that a function object name (function variable) and a normal variable name have the same specification. This variable can be referenced by the variable name, but the function variable name can be followed by brackets and parameter lists to make function calls.
It is not common to create a function in the form of new Function(), because a function body usually has multiple statements, and if they are passed as a string as a parameter, the code is poorly readable. The following is a syntax of its use:
The following is a quoted snippet:
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, body represents the function body statement of the created function, and 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 is a list 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:
The following is a quoted snippet:
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, which is determined by the JavaScript interpreter. The functions created through the above code can be called in the program using the function name. The function definition problem listed at the beginning of this section is also explained. Note that you can directly add brackets to the function declaration to indicate that the function call is immediately after the creation is completed, for example:
The following is a quoted snippet:
var i=function (a,b){
return a+b;
}(1,2);
alert(i);
This code will show that the value of variable i is equal to 3. i represents the returned value, not the created function, because the bracket "(" has a higher priority than the equal sign "=". Such code may not be commonly used, but this is a good solution when users want to modularize design in long code segments or want to avoid naming conflicts.
It should be noted that although the following two methods of creating functions are equivalent:
The following is a quoted snippet:
function funcName(){
//Function body
}
//Equivalent to
var funcName=function(){
//Function body
}
But the first method creates a named function, and the next method creates an unnamed function, just letting a variable point to the unnamed function. There is only one difference in use: for a named function, it can appear after the call and then be defined; for a named function, it must be defined before the call. For example:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
var func=function(){
alert(1)
}
//-->
</script>
This statement will produce a func undefined error, while:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
function func(){
alert(1)
}
//-->
</script>
It can be executed correctly, and the following statements can also be executed correctly:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
func();
var someFunc=function func(){
alert(1)
}
//-->
</script>
It can be seen that although JavaScript is an interpreted language, it checks whether there is a corresponding function definition in the entire code when calling a function. 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, and Error. These names actually represent a type and can be returned with an object through the new operator. However, function objects are different from other objects. When using typeof 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 examples the different types of typeof:
The following is a quoted snippet:
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 shows that the first 4 statements will display "function", while the next 3 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 Array, Object, etc. will return a normal object through the new operator. Although a function itself is an object, it is still different from an ordinary object because it is also an object constructor. That is to say, you can new a function to return an object, which has been introduced before. All objects that return "function" in typeof are function objects. Such objects are also called constructors, so all constructors are objects, but not all objects are constructors.
Since functions themselves are objects, their type is function, and when they are associated with object-oriented language definitions such as C++ and Java, you can guess the role of Function types, that is, you can define some methods and properties for the function object itself. With the help of the function prototype object, the definition of Function type can be easily modified and expanded. For example, the function type Function is expanded below and the method1 method is added to it. The function is to pop up the dialog box to display "function":
The following is a quoted snippet:
.method1=function(){
alert("function");
}
function func1(a,b,c){
return a+b+c;
}
func1.method1();
func1.method1.method1();
Note the last statement: func1.method1.mehotd1(), which calls the method1 method of the function object method1. Although it seems a bit confusing, it is still clear to look at the syntax after a closer look: 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 expansions of Function type have such recursive properties.
Function is the basis of all function objects, while Object is the basis of all objects (including function objects). In JavaScript, any object is an instance of Object. Therefore, you can modify the Object type to make all objects have some common properties and methods. Modifying the Object type is done through prototype:
The following is a quoted snippet:
=function(){
return typeof(this);
}
var array1=new Array();
function func1(a,b){
return a+b;
}
alert(());
alert(());
The above code adds a getType method to all objects, which is used to return the type of the object. The two alert statements will display "object" and "function" respectively.
Pass the function as a parameter
The nature of function objects has been introduced earlier. Each function is represented as a special object. It can be easily assigned to a variable and then function calls are made through this variable name. As a variable, it can be passed to another function as a parameter. This has been seen in the JavaScript event handling mechanism mentioned earlier. For example, the following program passes func1 as a parameter to func2:
The following is a quoted snippet:
function func1(theFunc){
theFunc();
}
function func2(){
alert("ok");
}
func1(func2);
In the last statement, func2 is passed as an object to func1's formal parameter theFunc, and then theFunc is called internally by func1. In fact, passing a function as a parameter, or assigning a function to other variables is the basis of all event mechanisms.
For example, if you need to do some initialization work when the page is loaded, you can first define an init initialization function, and then bind it to the event that the page is loaded through the =init; statement. The init here is a function object that can be added to the onload event list of window.
Implicit parameters passed to the function: arguments
When making a function call, in addition to the specified parameters, an implicit object is created - arguments. arguments is an object similar to an array but not an array. It is said that it is similar because it has the same access properties as an array. You can use syntax such as arguments[index] to get the value and have the array length attribute length property. The arguments object stores the parameters actually passed to the function, and is not limited to the parameter list defined by the function declaration, for example:
The following is a quoted snippet:
function func(a,b){
alert(a);
alert(b);
for(var i=0;i<;i++){
alert(arguments[i]);
}
}
func(1,2,3);
When the code is run, it will be displayed in sequence: 1, 2, 1, 2, 3. Therefore, when defining a function, even if the parameter list is not specified, the obtained parameters can still be referenced through arguments, which brings great flexibility to programming. Another property of the arguments object is callee, which represents a reference to the function object itself, which is conducive to the recursion of anonymous functions or to ensure the encapsulation of the function. For example, using recursion to calculate the sum of natural numbers from 1 to n:
The following is a quoted snippet:
var sum=function(n){
if(1==n)return 1;
else return n+sum(n-1);
}
alert(sum(100));
The function contains calls to sum itself. However, for JavaScript, the function name is just a variable name. Calling sum inside the function is equivalent to calling a global variable. It cannot be well reflected that it is calling itself, so using attributes is a better way:
The following is a quoted snippet:
var sum=function(n){
if(1==n)return 1;
else return n+(n-1);
}
alert(sum(100));
The callee attribute is not the only feature of arguments that differ from array objects. The following code shows that arguments are not created by the Array type:
The following is a quoted snippet:
.p1=1;
alert(new Array().p1);
function func(){
alert(arguments.p1);
}
func();
Running the code can find that the first alert statement is displayed as 1, which means that the array object has attribute p1, while the func call is displayed as "undefined", that is, p1 is not an attribute of arguments. It can be seen that arguments are not an array object.
The apply, call method and length attribute of the function
JavaScript defines two methods for function objects: apply and call. Their functions are to bind the function to another object to run. The two are only different in the way of defining parameters:
The following is a quoted snippet:
(thisArg,argArray);
(thisArg[,arg1[,arg2…]]);
From the function prototype, we can see that the first parameter is named thisArg, that is, this pointer inside all functions will be assigned to thisArg, which achieves the purpose of running the function as a method of another object. In addition to thisArg parameter, both methods are parameters passed for Function objects. The following code illustrates how apply and call methods work:
The following is a quoted snippet:
//Define a function func1, with attribute p and method A
function func1(){
="func1-";
=function(arg){
alert(+arg);
}
}
//Define a function func2, with attribute p and method B
function func2(){
="func2-";
=function(arg){
alert(+arg);
}
}
var obj1=new func1();
var obj2=new func2();
("byA"); //Show func1-byA
("byB"); //Show func2-byB
(obj2,["byA"]); //Show func2-byA, where ["byA"] is an array with only one element, the same below
(obj1,["byB"]); //Show func1-byB
(obj2,"byA"); //Show func2-byA
(obj1,"byB"); //Show func1-byB
It can be seen that after obj1's method A is bound to obj2 and run, the entire running environment of function A is transferred to obj2, that is, this pointer points to obj2. Similarly, function B of obj2 can also be bound to obj1 object to run. The last 4 lines of the code show the difference between the apply and call function parameter forms.
Unlike the length attribute of arguments, the function object also has a property length, which represents the number of parameters specified when the function is defined, rather than the number of parameters actually passed when the call is called. For example, the following code will show 2:
The following is a quoted snippet:
function sum(a,b){
return a+b;
}
alert();
Deeply understand this pointer in JavaScript
This pointer is an important concept in object-oriented programming, which represents the currently running object. When implementing an object's method, you can use this pointer to obtain a reference to the object itself.
Unlike other object-oriented languages, this pointer in JavaScript is a dynamic variable. This pointer in a method does not always point to the object that defines the method. There have been examples like this when talking about the apply and call methods of the function in the previous section. For easy understanding, let’s take a look at the following example:
The following is a quoted snippet:
<script language="JavaScript" type="text/javascript">
<!--
//Create two empty objects
var obj1=new Object();
var obj2=new Object();
//Add attribute p to both objects and equal to 1 and 2 respectively
=1;
=2;
//Add a method to obj1 to display the value of p
=function(){
alert(); //On the surface this pointer points to obj1
}
//Calling the getP method of obj1
();
// Make obj2's getP method equal to obj1's getP method
=;
//Calling the getP method of obj2
();
//-->
</script>
Judging from the execution results of the code, the dialog box pops up to display 1 and 2 respectively. It can be seen that the getP function is defined only once, run on different occasions, and displays different run results, which is determined by the change of this pointer. In obj1's getP method, this points to the obj1 object, and in obj2's getP method, this points to the obj2 object, and references the attribute p that both objects have through this pointer.
It can be seen that this pointer in JavaScript is a dynamically changing variable that indicates the object currently running the function. By the nature of this pointer, you can better understand the nature of objects in JavaScript: an object is a collection of one or more properties (methods). Each set element can not only belong to one set, but can dynamically belong to multiple sets. In this way, the pointer points to whom a method (collection element) is called. In fact, the apply method and call method introduced above are implemented by forcibly changing the value of this pointer, so that this pointer points to the object specified by the parameter, so as to run the method of one object as another object.
The elements (i.e. attributes or methods) of each object collection are also an independent part. There is no difference between a global function and a function defined as an object method, because global functions and variables can be regarded as methods and properties of window objects. You can also use the new operator to operate an object's method to return an object, so that the method of an object can be defined as a class, where this pointer will point to the newly created object. As you can see later, object names can play a namespace role at this time, which is a skill for object-oriented programming using JavaScript. For example:
The following is a quoted snippet:
var namespace1=new Object();
namespace1.class1=function(){
//Initialize the object code
}
var obj1=new namespace1.class1();
Here you can regard namespace1 as a namespace.
Due to the dynamic change characteristics of object properties (methods), the reference between two properties (methods) of an object must be passed through this pointer, while in other languages, this keyword can be omitted. As in the example above:
The following is a quoted snippet:
=function(){
alert(); //On the surface this pointer points to obj1