Understand the use of functions in JavaScript

Source: Internet
Author: User
Tags access properties

Functions are the basis for modular programming, and for writing complex AJAX applications, you must have a deeper understanding of the functions.

The functions in JavaScript are different from those of 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 pass the function as a parameter. Before continuing, take a look at the usage 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 differ greatly from functions that are common in other languages or the way they are defined earlier. So why would you write that in JavaScript? What is the syntax it follows? These are described in the following sections.

Recognizing function objects (functions object)

You can define a function with the function keyword and specify a function name for each function, which is called by the name. When JavaScript interprets execution, the function is maintained as an object, which is the function object to be introduced.

A function object is fundamentally different from other user-defined objects, which are called internal objects, such as date objects (dates), array objects (arrays), and string objects (strings). The constructors for these built-in objects are defined by JavaScript itself: by executing a statement such as the new Array (), an object is returned, and there is a set of mechanisms within JavaScript to initialize the returned object, rather than the user specifying how the object is constructed.

In JavaScript, the function object corresponds to the type of functions, just as the array object corresponds to the type is an array, the Date object corresponds to the same type as date, you can create a function object by using 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 array objects. Look at the Array object first: The following two lines of code create an array object myarray:

var myarray=[];

Equivalent to

var myarray=new Array ();

Similarly, the following two-segment code also creates a function MyFunction:

function MyFunction (A, b) {

return a+b;

}

Equivalent to

var myfunction=new Function ("A", "B", "Return A+b");

Through the comparison with the construction of the array object statement, you can clearly see the function object essence, the function declaration described above is the first way of the above code, and inside the interpreter, when encountering this syntax, it will automatically construct a function object, which functions as an internal object to store and run. As can be seen here, a function object name (function variable) and a normal variable name have the same specification, you can refer to this variable by the variable name, but after the function variable name can follow the parentheses and the argument list to make function calls.

Creating a function in the form of new function () is uncommon because a function body usually has more than one statement, and if you pass them as arguments as a string, the readability of the code is poor. 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 PN represents the list of parameter names of the created function, body represents the function body statement of the created function, and funcname is the name of the function being created. You can create an empty function without specifying any arguments, and do not specify funcname to create a nameless function, which of course does not have any meaning.

It should be noted that P1 to PN is a list of parameter names, that is, P1 not only represents a parameter, it can also be a comma-separated list of arguments, 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 a function type and provides a syntax such as the new function () because the function object must use the type of functions to add properties and methods.

The essence of a function is an internal object that the JavaScript interpreter determines how it runs. Functions created by the code above 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 enclose the function declaration with parentheses to make the function call immediately after the creation is complete, for example:

var i=function (A, b) {

return a+b;

} (for each);

alert (i);

This code will show that the value of the variable I equals 3. I is the value returned, not the created function, because the parentheses "(" is higher precedence than the equals sign "=". Such code may not be common, but it is a good solution when users want to design a module in a long code snippet or avoid naming conflicts.

It is important to note that although the following two methods of creating functions are equivalent:

function FuncName () {

function body

}

Equivalent to

var funcname=function () {

function body

}

But the first way to create a well-known function is to create a nameless function, just to have a variable point to the Nameless function. There is only a small difference in usage: for a well-known function, it can be defined after the call, and for the nameless function, it must have been defined before the call. For example:

!--

Func ();

var func=function () {

Alert (1)

}

-->

This statement generates a Func undefined error, and:

!--

Func ();

function func () {

Alert (1)

}

-->

Can be executed correctly, the following statements are also executed correctly:

!--

Func ();

var somefunc=function func () {

Alert (1)

}

-->

This shows that although JavaScript is an interpreted language, it will check the entire code for a function definition when it is called, only if the function name is defined through function funcName (), and cannot be an anonymous function.

Relationship of function object 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. The function object, however, differs from other objects in that it returns the string "function" when using typeof to get the type of a function object, and returns the string "Object" when typeof an array object or other object. The following code example typeof different types of situations:

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 can be found: the previous 4 statements will show "function", and the next 3 statements will display "object", so that the new function is actually returned a function. This differs greatly from other objects. The other types array, object, and so on, return a normal object through 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, you can return an object with a new function, as described earlier. All objects that typeof return "function" are function objects. This 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 function, think of C + +, Java and other object-oriented language class definitions, can guess the function of the function type, it is possible to define some methods and properties of the functions of the object itself, with the help of the function of the Prototype object, it is easy to modify and expand the definition of function type, for example, the following extension functions type, for which the Method1 method is added, the function is to pop up the 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 ();

Note the last statement: FUNC1.METHOD1.MEHOTD1 (), which invokes the Method1 method that method1 this function object. While it may seem a bit confusing, it's clear to look at the syntax: This is a recursive definition. Because METHOD1 itself is also a function, it also has the properties and methods of the function object, all of which have the recursive nature of the method extensions for the type of functions.

Functions are 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 have some common properties and methods for all objects, and modifying the object type is done by 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 the GetType method to all objects, which returns the type of the object. The two alert statements show "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, it can be easily assigned to a variable, and then through the variable name for function calls. As a variable, it can be passed as an argument to another function, which has been seen in the previous JavaScript event handling mechanism, such as the following program passing 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, and the Thefunc call is made internally by 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 work on page loading, you can define an init function for initialization and then bind it to a page load-completed event by Window.onload=init. The init here is a function object that can be added to the OnLoad Event List of window.

Implied arguments passed to the function: arguments

When a function call is made, an implied object--arguments is created in addition to the specified arguments. Arguments is an array-like but not an array object, saying that it is similar because it has an array of access properties, can be used arguments [index] such a syntax to take a value, the length of the array of properties. The arguments object stores parameters that are actually passed to the function, not limited to the list of parameters defined by the function declaration, for example:

function Func (A, b) {

alert (a);

alert (b);

for (Var i=0;i

Alert (Arguments[i]);

}

}

Func (n/a);

When the code runs, it is displayed in turn: 1,2,1,2,3. Therefore, when defining a function, even if you do not specify a parameter list, you can still refer to the obtained parameters by arguments, 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 recursion of the nameless function or guarantees the encapsulation of the function, such as the sum of the natural numbers of 1 to n calculated using recursion:

var sum=function (n) {

if (1==n) return 1;

else return n+sum (n-1);

}

Alert (sum (100));

Where the function inside contains a call to the sum itself, but for JavaScript, the function name is just a variable name, calling sum inside a function is equivalent to calling a global variable, which is not a good representation of calling itself. So using the Arguments.callee attribute would be a better approach:

var sum=function (n) {

if (1==n) return 1;

else return N+arguments.callee (n-1);

}

Alert (sum (100));

The callee property is not unique to arguments unlike array objects, and the following code illustrates that arguments is not created by the array type:

Array.prototype.p1=1;

Alert (new Array (). p1);

function func () {

alert (ARGUMENTS.P1);

}

Func ();

Running the code can be found that the first alert statement is displayed as 1, which means that the array object has the property P1, and the Func call is displayed as "undefined", that is P1 is not a arguments attribute, 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 are used to bind a function to another object, and they differ only in the way that the parameters are defined:

Function.prototype.apply (Thisarg,argarray);

Function.prototype.call (Thisarg[,arg1[,arg2 ...]);

As you can see from the function prototype, the first parameter is named Thisarg, which means that the this pointer inside all functions is assigned a value of Thisarg, which implements the purpose of running the function as a method of another object. Two methods except for 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 properties p and method a

function Func1 () {

this.p= "func1-";

This. A=function (ARG) {

alert (THIS.P+ARG);

}

}

Defines a function Func2, with properties 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"]); Display 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 running environment is transferred to the OBJ2, that is, the this pointer points to the OBJ2. The same obj2 function B can also be bound to the Obj1 object to run. The last 4 lines of code show the differences in the form of the Apply and call function parameters.

Unlike the length property of arguments, the function object also has a property length, which represents the number of parameters that are specified when the function is defined, rather than the number of arguments that were actually passed when it was transferred. For example, the following code will show 2:

function sum (A, b) {

return a+b;

}

alert (sum.length);

In-depth understanding of the this pointer in JavaScript

The this pointer is an important concept in object-oriented programming, which represents the currently running object. When implementing 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 in 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, take a look at the following example:

!--

Create two empty objects

var obj1=new Object ();

var obj2=new Object ();

Add attribute p to all two objects and equals 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 Getp method of Obj1

OBJ1.GETP ();

To 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 ();

-->

From the execution results of the Code, the popup dialog shows 1 and 2 respectively. Thus, the GETP function is defined only once, runs on different occasions, shows different running results, which is determined by the change of 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 this pointer refers to the property P that all two objects have.

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 the object in JavaScript: An object is a collection of one or more properties (methods). Each collection element does not belong to only one collection, but can belong to multiple collections dynamically. Thus, a method (the collection element) is called 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 the object specified by the parameter, so that the method of one object is run as a method of another object.

The element of each object collection (that is, a property or method) is also a separate part, and there is no difference between a global function and a function defined as an object method, because global functions and variables can be thought of as methods and properties of the Window object. You can also use the new operator to manipulate an object's methods to return an object, so that the method of an object can 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 play a role in a namespace, which is a technique for object-oriented programming using JavaScript. For example:

var namespace1=new Object ();

Namespace1.class1=function () {

Code to initialize the object

}

var obj1=new namespace1.class1 ();

Here you can think of Namespace1 as a namespace.

Because of the dynamic nature of the object's properties (methods), the reference between the two properties (methods) of an object must pass through the this pointer, while 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, rather than the Obj1 property.

Understand the use of functions in JavaScript

Related Article

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.