The Essentials of Learning JavaScript

Source: Internet
Author: User
Tags access properties

-------------------This digest from the Anonymous tutorial summary, I hope to beginners JS students have help, because it solves my Learning js many confusing ...


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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
<script language= "JavaScript" type= "Text/javascript" >
!--
Func ();
var func=function () {
Alert (1)
}
-->
</script>

This statement generates a Func undefined error, and:

The following is a reference fragment:
<script language= "JavaScript" type= "Text/javascript" >
!--
Func ();
function func () {
Alert (1)
}
-->
</script>

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

The following is a reference fragment:
<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 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:

The following is a reference fragment:
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, associating to C + +, Java and other object-oriented language class definition, you can guess the function of the function type, that is, you can define some methods and properties of the functional object itself, With the help of the prototype object of the function, it is convenient to modify and extend the definition of the function type, for example, the following extends the functions type, and adds the Method1 method to it, the function is that the popup dialog displays "function":

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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 it is similar because it has an array of access properties, you can use the syntax such as Arguments[index] 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:

The following is a reference fragment:
function Func (A, b) {
alert (a);
alert (b);
for (Var i=0;i<arguments.length;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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
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:

The following is a reference fragment:
function sum (A, b) {
return a+b;
}
alert (sum.length);

Prerequisites for Learning 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.