A deep understanding of function _javascript techniques in JavaScript

Source: Internet
Author: User
Tags array length class definition function definition function prototype
Overview
function is the basis of modular programming, writing complex AJAX applications, you must have a more in-depth understanding of the function. Functions in JavaScript are different from other languages, and each function is maintained and run as an object. By the nature of the function object, it is convenient to assign a function to a variable or to pass the function as a parameter. Before continuing, take a look at the use syntax of the function:
function Func1 (...) {...}
var func2=function (...) {...};
var func3=function func4 (...) {...};
var func5=new Function ();
These are the correct syntax for declaring a function. They are very different from functions that are common in other languages, or functions that are previously described. So why do you write that in JavaScript? What is the syntax it follows? These are described below.
Understanding Function Objects (functions object)
You can define a function by using the function keyword, and specify a function name for each function, which is invoked by the name of the functions. When JavaScript interprets execution, the function is maintained as an object, which is the function object to introduce.
function objects are essentially different from other users ' defined objects, which are called internal objects, such as date objects (dates), array objects (array), string objects (strings), which are internal objects. The constructors for these built-in objects are defined by JavaScript itself: returning an object by executing a statement such as the new Array (), where JavaScript has a mechanism to initialize the returned object rather than the user specifying how the object is constructed.
In JavaScript, the type of the function object corresponds to functions, just as the type of the array object is the array, and the Date object corresponds to the type date, and you can create a function object by using the new function (). You can also create an object by using the function keyword. For ease of understanding, we compare the creation of function objects and the creation of arrays of objects. First look at the array object: The following two lines of code are to create an array object myarray:
var myarray=[];
Equivalent to
var myarray=new Array ();
Again, the following two pieces of code create a function MyFunction:
function MyFunction (a,b) {
return a+b;
}
Equivalent to
var myfunction=new Function ("A", "B", "Return A+b");
By comparing and constructing the Array object statement, you can clearly see the nature of the function object, the function declaration described earlier is the first way of the above code, but inside the interpreter, when this syntax is encountered, a function object is automatically constructed and stored and run as an internal object. As you can see here, a Function object name (function variable) and a normal variable name have the same specification, can be referenced by variable name to this variable, but the function variable name can be followed by parentheses and argument list for function calls.
Creating a function in the form of the new function () is uncommon because a function body usually has multiple statements that, if passed as a string, are not readable by the code. Here's how to use the syntax:
var funcname=new Function (p1,p2,..., pn,body);
The type of the parameter is a string, p1 to the list of parameter names for the function created by the PN, and the body represents the function statement of the function being created, FuncName is the name of the function being created. You can create an empty function without specifying any parameters, and do not specify funcname to create a nameless function, of course, that function has no meaning.
Note that P1 to PN is a list of parameter names, that is, P1 not only represents an argument, it can also be a comma-separated list of arguments, such as 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")
The syntax for JavaScript to introduce a function type and provide a new function () is because the function object adds properties and methods that must rely on the type of function.
The essence of a function is an internal object that determines how it is run by the JavaScript interpreter. Functions created from the above code can be invoked in a program using the name of the function. The function definition issues listed at the beginning of this section are also explained. Note You can add parentheses directly after a function declaration to indicate that a function call is made immediately after the creation completes, for example:
var i=function (a,b) {
return a+b;
} (1,2);
alert (i);
This code will show that the value of variable I equals 3. I is the value that is returned, not the function created, because the parentheses "(") have a higher priority than the equals sign = ". Such code may not be commonly used, but this is a good solution when users want to design a module in a long piece of code or want to avoid naming conflicts.
It is worth noting that although the following two methods of creating functions are equivalent:
function FuncName () {
function body
}
Equivalent to
var funcname=function () {
function body
}
But one way to do this is to create a well-known function, and then create a nameless function, and just let a variable point to the Nameless function. There is only one difference in use: For a well-known function, it can be defined after the call, and for the nameless function it must be defined before the call. For example:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Func ();
var func=function () {
Alert (1)
}
-->
</script>
This statement will produce Func undefined errors, and:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Func ();
function func () {
Alert (1)
}
-->
</script>
is executed correctly, the following statement can also be executed correctly:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Func ();
var somefunc=function func () {
Alert (1)
}
-->
</script>
This shows that although JavaScript is an interpreted language, it will check the entire code for the existence of a function definition in the function call, which is only valid through the function funcName () definition, not an anonymous function.
Relationship of function objects and other internal objects
In addition to the function object, there are many internal objects, such as Object, Array, Date, RegExp, Math, and Error. These names actually represent a type, and you can return an object by using the new operator. However, unlike other objects, the function object will still return the string "function" when it typeof the type of a function object, and it will return the string "Object" when typeof an array object or other object. The following code example typeof different types of cases:
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 will reveal that the first 4 statements will display "function", and the following 3 statements show "Object", which shows that the new function actually returns a function. This is a lot different from other objects. Other types array, object, and so on will return a normal object via the new operator. Although the function itself is an object, it differs from a normal object because it is also an object constructor, that is, a function can be used to return an object, as described earlier. All TypeOf objects that return "function" are function objects. The object is also called a constructor (constructor), so all constructors are objects, but not all objects are constructors.
Since the function itself is also an object, their type is a function, Lenovo to the C + +, Java, and other object-oriented language class definition, you can guess the role of the function type, that is, you can give the function object itself to define some methods and properties, The prototype object of a function makes it easy to modify and extend the definition of a function type, for example, by extending the functional type functions, adding a method1 method to the pop-up dialog box that displays "function":
Function.prototype.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 method1 this function object. While it may seem a little confusing, it is clear that a careful look at the syntax: This is a recursive definition. Because the method1 itself is also a function, it also has the properties and methods of the function object, all of which have such a recursive property for the extension of the method of the functions type.
A function is the basis for all function objects, and object is the basis for all objects, including function objects. In JavaScript, any object is an instance of object, so you can modify the type of object to allow all objects to have some common properties and methods, and modifying the object type is done through prototype:
Object.prototype.gettype=function () {
Return typeof (This);
}
var array1=new Array ();
function Func1 (a,b) {
return a+b;
}
Alert (Array1.gettype ());
Alert (Func1.gettype ());
The above code adds a GetType method to all objects, which is to return the type of the object. The two alert statements display "Object" and "function" respectively.
Passing a function as a parameter
In the previous introduction of the function object essence, each function is represented as a special object, you can easily assign it to a variable, and then through the variable name for function calls. As a variable, it can be passed as a parameter to another function, as described earlier in 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 FUNC1 's formal parameter thefunc, which is then invoked by Thefunc inside the func1. In fact, passing a function as a parameter, or assigning a function to another variable, is the basis of all event mechanisms.
For example, if you need to do some initialization while the page is loading, you can define an INIT initialization function and then bind it to the page load-completed event by using the Window.onload=init statement. Init here is a function object that can be added to the list of onload events for Windows.
Implied parameters passed to the function: arguments
When a function call is made, an implied object--arguments is created in addition to the specified parameters. Arguments is a similar array but not an array object, saying it is similar because it has an array-like Access property, you can use the syntax such as Arguments[index to take the value of the array length attribute length. The arguments object stores the arguments that are actually passed to the function, rather than the list of parameters defined by the function declaration, for example:
function func (a,b) {
alert (a);
alert (b);
for (Var i=0;i<arguments.length;i++) {
Alert (Arguments[i]);
}
}
Func (1,2,3);
The code is run in turn: 1,2,1,2,3. Therefore, when you define a function, you can still refer to the obtained parameter by arguments, even if you do not specify a parameter list, which gives you a lot of flexibility in programming. Another property of the arguments object is callee, which represents a reference to the function object itself, which facilitates the recursion of nameless functions or the encapsulation of functions, such as using recursion to compute the sum of the natural numbers of 1 to N:
var sum=function (n) {
if (1==n) return 1;
else return n+sum (n-1);
}
Alert (sum (100));
Inside the function contains the call to sum itself, but for JavaScript, the function name is just a variable name, and calling sum within the function is equivalent to calling a global variable, which is not a good representation of the call itself. So using the Arguments.callee attribute would be a good idea:
var sum=function (n) {
if (1==n) return 1;
else return N+arguments.callee (n-1);
}
Alert (sum (100));
The callee property is not arguments unique to an array object, and the following code shows that arguments is not created by the array type:
Array.prototype.p1=1;
Alert (new Array (). p1);
function func () {
alert (ARGUMENTS.P1);
}
Func ();
The run code can find that the first alert statement is displayed as 1, meaning that the array object owns the property P1, and the Func call is displayed as "undefined", that is, P1 is not a arguments property, thus, arguments is not an array object.
The Apply, call method, and length property of a function
JavaScript defines two methods for a function object: Apply and call, which function by binding a function to another object, which differs only in the way that the parameter is defined:
Function.prototype.apply (Thisarg,argarray);
Function.prototype.call (Thisarg[,arg1[,arg2 ...]);
As you can see from the function prototype, the first argument is named Thisarg, that is, the this pointer within all functions is assigned to THISARG, which enables you to run the function as a method of another object. Two methods except the Thisarg parameter, are the parameters passed for the function object. The following code illustrates how the Apply and call methods work:
Defines a function func1, with attribute p and method a
function Func1 () {
this.p= "func1-";
This. A=function (ARG) {
alert (THIS.P+ARG);
}
}
Defines a function func2, with attribute p and method b
function Func2 () {
this.p= "func2-";
This. B=function (ARG) {
alert (THIS.P+ARG);
}
}
var obj1=new func1 ();
var obj2=new func2 ();
Obj1.    A ("Bya"); Show Func1-bya
Obj2.    B ("Byb"); Show Func2-byb
Obj1. A.apply (obj2,["bya"]); Displays Func2-bya, where ["Bya"] is an array of only one element, the same as
Obj2. B.apply (obj1,["BYB"]); Show Func1-byb
Obj1.  A.call (Obj2, "bya"); Show Func2-bya
Obj2.  B.call (obj1, "byb"); Show Func1-byb
As can be seen, Obj1 's method A is bound to the OBJ2 run, the entire function A's operating environment is shifted to the obj2, that is, the this pointer points to OBJ2. The same obj2 function B can also be bound to the Obj1 object to run. The last 4 lines of code show the difference between the form of apply and call function arguments.
Unlike the length property of the arguments, the function object also has a property length that represents the number of parameters that are specified when the function is defined, not the number of arguments actually passed when it was invoked. For example, the following code will show 2:
function sum (a,b) {
return a+b;
}
alert (sum.length);

Learn more about the this pointer in JavaScript
The this pointer is an important concept in object-oriented programming that represents the currently running object. When you implement a method of an object, you can use the this pointer to obtain a reference to the object itself.
Unlike other object-oriented languages, the This pointer in JavaScript is a dynamic variable, and the this pointer within a method does not always point to the object that defines the method, as has been the case with the apply and call methods of the function in the previous section. To facilitate understanding, look at the following example:
<script language= "JavaScript" type= "Text/javascript" >
<!--
Create two empty objects
var obj1=new Object ();
var obj2=new Object ();
Add attribute p to all two objects, equal to 1 and 2 respectively
Obj1.p=1;
obj2.p=2;
Add a method to Obj1 to display the value of P
Obj1.getp=function () {
alert (THIS.P); On the surface the this pointer is pointing to the obj1
}
Call the Obj1 Getp method
OBJ1.GETP ();
Getp method to make Obj2 Getp method equal to Obj1
OBJ2.GETP=OBJ1.GETP;
Call the Obj2 Getp method
OBJ2.GETP ();
-->
</script>
From the execution results of the Code, pop-up dialog boxes display 1 and 2, respectively. This shows that the GETP function is defined only once, runs on different occasions, and shows different running results, which is determined by the change of this pointer. In the Obj1 Getp method, this points to the Obj1 object, and in the Obj2 Getp method, this points to the Obj2 object and refers to the property P with two objects through the this pointer.
Thus, the this pointer in JavaScript is a dynamically changing variable that indicates the object that is currently running the function. By the nature of this pointer, you can also better understand the nature of objects in JavaScript: An object is a collection of one or more attributes (methods). Each collection element is not capable of belonging to only one set, but can be dynamic to more than one set. This way, a method (the collection Element) is invoked by WHO, and the this pointer points to WHO. In fact, both the Apply method and the call method described earlier are implemented by forcing the value of the this pointer to be changed, so that the this pointer points to the object specified by the parameter to run the method of one object as another object.
The elements of each collection of objects (that is, attributes or methods) are also separate parts, and there is no difference between global functions and functions defined as an object method, because global functions and variables can be treated as methods and properties of Window objects. You can also use the new operator to manipulate the method of an object to return an object, so that the method of an object can also be defined as the form of a class, where the this pointer points to the newly created object. As you can see later, object names can act as a namespace, a technique for object-oriented programming using JavaScript. For example:
var namespace1=new Object ();
Namespace1.class1=function () {
Initializing the object's code
}
var obj1=new namespace1.class1 ();
Here you can think of Namespace1 as a namespace.
Because of the dynamic nature of the object property (method), the reference to each other of the two properties (methods) of an object must pass through the this pointer, and in other languages the This keyword can be omitted. As in the above example:
Obj1.getp=function () {
alert (THIS.P); On the surface the this pointer is pointing to the obj1
}
The This keyword here is not to be omitted, that is, the form of alert (p) cannot be written. This will allow the GETP function to refer to the P variable in the context, not the Obj1 attribute.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.