Essential to learning JavaScript (1), so that you are no longer confused about JS functions, JavaScript built-in objects, and the concept and relationship between this. (I hope I can set it as a recommendation article for more JS beginners)

Source: Internet
Author: User

------------------- The abstract is based on the anonymous tutorial summary. I hope it will help beginners in JS, because it solves the many puzzles I learned about Js...

Functions are the basis for modular program design. To compile 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 proceeding, let's take a look at the usage syntax of the function:

The following is a reference clip:
Function func1 (...) {...}
VaR func2 = function (...) {...};
VaR func3 = function func4 (...) {...};
VaR func5 = new function ();

These are the correct syntax for declaring functions. They differ greatly from common functions in other languages or previously described function definition methods. So why can this be written in JavaScript? What is the syntax it follows? The following describes the content.

Understanding function objects)

You can use the function keyword to define a function, specify a function name for each function, and call it through the function name. During JavaScript interpretation and execution, functions are maintained as an object, which is the function object to be introduced ).

Function objects are essentially different from other user-defined objects. Such objects are called internal objects, such as date, array, and string objects) all belong to internal objects. The constructor of these built-in objects is defined by JavaScript itself: an object is returned by executing a statement such as new array (). Javascript has a set of internal mechanisms to initialize the returned object, instead of specifying the object construction method by the user.

In JavaScript, function objects correspond to the function type. Just as array objects correspond to the array type and date objects correspond to the date type, you can use the new function () create a function object. You can also use the function keyword to create an object. For ease of understanding, we compare the creation of function objects and the creation of array objects. First look at the array object: The following two lines of code are to create an array object myarray:

The following is a reference clip:
VaR myarray = [];
// Equivalent
VaR myarray = new array ();
Similarly, the following two sections of code also create a function myfunction:
Function myfunction (a, B ){
Return A + B;
}
// Equivalent
VaR myfunction = new function ("A", "B", "Return A + B ");

By comparing with the statements used to construct an array object, you can clearly see the essence of the function object. The function declaration described earlier is the first method of the above Code. Inside the interpreter, when this syntax is used, a function object is automatically constructed to store and run the function as an internal object. You can also see that a function object name (function variable) and a common variable name share the same specification and can reference this variable through the variable name, however, function variable names can be followed by brackets and parameter lists for function calling.

It is uncommon 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 code is less readable. The following describes the Syntax:

The following is a reference clip:
VaR funcname = new function (P1, P2,..., Pn, body );

The parameter types are all strings. P1 to PN indicates the list of parameter names of the created function, body indicates the function body statement of the created function, and funcname indicates the name of the created function. You can create an empty function without specifying any parameters, and create an unknown function without specifying funcname. Of course, such a function does not make any sense.

It should be noted that P1 to PN is a list of parameter names, that is, P1 can represent not only a parameter, but also a list of parameters separated by commas, for example, the following definition is equivalent:

The following is a reference clip:
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 the syntax of new function () Because function objects must be of the function type when adding attributes and methods.

The essence of a function is an internal object, which is determined by the javascript interpreter. Functions created using the code above can be called using the function name in the program. The function definition problems listed at the beginning of this section are also explained. Note that you can add parentheses after the function declaration to call the function immediately after the creation is complete. For example:

The following is a reference clip:
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 indicates the returned value, rather than the created function, because the brackets "(" has a higher priority than the equal sign "=. Such Code may not be commonly used, but it is a good solution when users want to implement modular design in a long code segment or want to avoid name conflicts.

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

The following is a reference clip:
Function funcname (){
// Function body
}
// Equivalent
VaR funcname = function (){
// Function body
}

However, the previous method is to create a famous function, while the latter is to create an unknown function, just to point a variable to this unknown function. There is only one difference in usage: For a famous function, it can be defined after it is called. For an unknown function, it must be defined before it is called. For example:

The following is a reference clip:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Func ();
VaR func = function (){
Alert (1)
}
// -->
</SCRIPT>

This statement will generate an undefined error in func, and:

The following is a reference clip:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
Func ();
Function func (){
Alert (1)
}
// -->
</SCRIPT>

The statement can be correctly executed, and the following statement can also be correctly executed:

The following is a reference clip:
<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 will check whether the corresponding function definition exists in the entire code During function calling. This function name only uses function funcname () the format defined is valid, but not an anonymous function.

Relationship Between Function objects and other internal objects

In addition to function objects, there are also many internal objects, such as object, array, date, Regexp, math, and 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 obtain the type of a function object, it still returns the string "function", while typeof is an array object or another object, it returns the string "object ". The following code demonstrates different types of typeof:

The following is a reference clip:
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 ()));

After running this code, we can find that all the first four statements show "function", and the last three statements show "object". It can be seen that a new function actually returns a function. This is quite different from other objects. Other types of arrays and objects will return a common object through the new operator. Although a function is also an object, it is different from a common object because it is also an object constructor. That is to say, you can use a new function to return an object, this is already described earlier. All typeof objects that return "function" are function objects. This is also called constructor. Therefore, all constructors are objects, but not all objects are constructors.

Since functions are also an object, their types are functions, and the class definitions of C ++, Java, and other object-oriented languages can be inferred to the role of function types, that is, some methods and attributes can be defined for the function object itself. With the help of the prototype object of the function, you can easily modify and expand the definition of the function type. For example, the following extends the function type function, the Method1 method is added for it. The pop-up dialog box displays "function ":

The following is a reference clip:
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 the Method1 function object. Although it may seem confusing, the syntax is clear: this is a recursive definition. Because Method1 is also a function, it also has the attributes and methods of function objects. All method extensions of function types 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 object instance. Therefore, you can modify the object type to make all objects have some common attributes and methods, you can modify the object type through prototype:

The following is a reference clip:
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 the GetType method to all objects to return the object type. The two alert statements show "object" and "function" respectively ".

Passing functions as parameters

We have already introduced the essence of function objects. Each function is represented as a special object, which can be conveniently assigned to a variable and then called by the variable name. As a variable, it can be passed to another function in the form of parameters. This usage has been seen in the Javascript event processing mechanism described earlier, for example, the following program passes func1 as a parameter to func2:

The following is a reference clip:
Function func1 (thefunc ){
Thefunc ();
}
Function func2 (){
Alert ("OK ");
}
Func1 (func2 );

In the last statement, func2 is passed to thefunc as an object, 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 initialization during page loading, You can first define an init initialization function and then use window. onload = Init; the statement binds it to the event loaded on the page. Init is a function object, which can be added to the onload event list of window.

Implicit parameter passed to the function: arguments

When you call a function, in addition to the specified parameters, you can also create an implicit object, arguments. Arguments is an object similar to an array but not an array. It is similar because it has the same access nature as an array. You can use the syntax values such as arguments [Index] to obtain the Length attribute of an array. The arguments object stores the parameters actually passed to the function, not limited to the list of parameters defined in the function declaration. For example:

The following is a reference clip:
Function func (a, B ){
Alert ();
Alert (B );
For (VAR I = 0; I <arguments. length; I ++ ){
Alert (arguments [I]);
}
}
Func (1, 2, 3 );

When the code is run, the following values are displayed: 1, 2, 2, 3. Therefore, when defining a function, you can still reference the obtained parameters through arguments even if you do not specify the parameter list, which brings great flexibility to programming. Another attribute of the arguments object is callee, which indicates the reference to the function object itself, which is conducive to recursion of the unknown function or guarantee the function encapsulation, for example, recursion is used to calculate the sum of Natural Numbers 1 to n:

The following is a reference clip:
VaR sum = function (n ){
If (1 = N) return 1;
Else return N + sum (n-1 );
}
Alert (sum (1, 100 ));

The function contains a call to sum itself. However, for Javascript, the function name is only a variable name. Calling sum within the function is equivalent to calling a global variable, it cannot be reflected that it is called itself, so arguments is used. the callee attribute is a good method:

The following is a reference clip:
VaR sum = function (n ){
If (1 = N) return 1;
Else return N + arguments. callee (n-1 );
}
Alert (sum (1, 100 ));

The callee attribute is not the only feature of arguments different from the array object. The following Code shows that arguments is not created by the array type:

The following is a reference clip:
Array. Prototype. p1 = 1;
Alert (new array (). P1 );
Function func (){
Alert (arguments. P1 );
}
Func ();

Run the code to find that the first alert statement is 1, indicating that the array object has the attribute P1, while the func call is "undefined", that is, P1 is not the attribute of arguments, arguments is not an array object.

Apply, call, and length attributes of the Function

Javascript defines two methods for function objects: Apply and call. They are used to bind the function to another object for running. The two methods are different only when defining parameters:

The following is a reference clip:
Function. Prototype. Apply (thisarg, argarray );
Function. Prototype. Call (thisarg [, arg1 [, arg2…]);

From the function prototype, we can see that the first parameter is named thisarg, that is, the this pointer inside all functions will be assigned thisarg, this achieves the purpose of running a function as another object. The 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:

The following is a reference clip:
// Define a function func1 with the property P and method
Function func1 (){
This. P = "func1 -";
This. A = function (ARG ){
Alert (this. P + Arg );
}
}
// Define a function func2 with the property 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"); // display func1-byA
Obj2. B ("Byb"); // display func2-byB
Obj1.a. Apply (obj2, ["bya"]); // display the func2-byA, where ["bya"] is an array with only one element, the same below
Obj2. B. Apply (obj1, ["Byb"]); // display func1-byB
Obj1.a. Call (obj2, "bya"); // display func2-byA
Obj2. B. Call (obj1, "Byb"); // display func1-byB

It can be seen that after method A of obj1 is bound to obj2 for running, the runtime environment of function a is transferred to obj2, that is, this Pointer Points to obj2. Similarly, function B of obj2 can be bound to the obj1 object for running. The last four lines of the Code show the differences between the parameters of the apply and call functions.

Different from the Length attribute of arguments, the function object also has an attribute length, which indicates the number of parameters specified during Function Definition, rather than the number of parameters actually passed during the call. For example, the following code shows 2:

The following is a reference clip:
Function sum (a, B ){
Return A + B;
}
Alert (sum. Length );

In-depth understanding of this pointer in Javascript

This pointer is an important concept in object-oriented programming. It represents the currently running object. When implementing the object method, you can use the this pointer to obtain the reference of 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 this method, in the previous section, we used the apply and call methods of functions. For ease of understanding, let's look at the following example:

The following is a reference clip:
<Script language = "JavaScript" type = "text/JavaScript">
<! --
// Create two empty objects
VaR obj1 = new object ();
VaR obj2 = new object ();
// Add the property P to both objects, which is 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, this Pointer Points to obj1
}
// Call the getp method of obj1
Obj1.getp ();
// Make the getp method of obj2 equal to the getp method of obj1
Obj2.getp = obj1.getp;
// Call the getp method of obj2
Obj2.getp ();
// -->
</SCRIPT>

From the code execution results, the pop-up dialog box displays 1 and 2 respectively. It can be seen that the getp function is defined only once and runs on different occasions and shows different running results, which is determined by the change of the this pointer. In the getp method of obj1, this points to the obj1 object, and in the getp method of obj2, this points to the obj2 object, and the property P of both objects is referenced through the this pointer.

It can be seen that the this pointer in Javascript is a dynamically changing variable, which indicates the object currently running this function. By the nature of this pointer, you can better understand the nature of objects in javascript: an object is a set of one or more attributes (methods. Each set element can not only belong to one set, but dynamically belongs to multiple sets. In this way, the this pointer directs to the person who calls a method (set element. In fact, both the apply and call methods described above are implemented by forcibly changing the value of this pointer so that this pointer points to the object specified by the parameter, in this way, the method of one object is run as the method of another object.

Each element (attribute or method) in an object set is 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 viewed as methods and attributes of window objects. You can also use the new operator to operate an object method to return an object, so that an object method can be defined as a class, the this pointer points to the newly created object. As you can see later, the object name can act as a namespace, which is a technique for object-oriented programming using JavaScript. For example:

The following is a reference clip:
VaR namespace1 = new object ();
Namespace1.class1 = function (){
// Initialize the object code
}
VaR obj1 = new namespace1.class1 ();

Here we can regard namespace1 as a namespace.

Because of the dynamic variation of object attributes (methods), mutual reference between two attributes (methods) of an object must pass the this pointer. In other languages, this keyword can be omitted. In the above example:

The following is a reference clip:
Obj1.getp = function (){
Alert (this. p); // on the surface, this Pointer Points to obj1

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.