Reading notes---Functions of advanced JavaScript programming

Source: Internet
Author: User
Tags diff

Function
Functions are a core concept for any language. Functions can encapsulate any number of statements, and can be invoked anywhere, at any time, to execute. Functions in ECMAScript are declared by using the function keyword followed by a set of parameters and the body of the function.
The basic syntax for a function is as follows:

function functionname (arg0, arg1,..., ArgN) {
Statements
}
The following is an example of a function:
function Sayhi (name, message) {
Alert ("Hello" + name + "," + message);
}

This function can be called by its function name, followed by a pair of parentheses and arguments (if there are more than one parameter in the parentheses, it can be separated by commas). The code for calling the Sayhi () function is as follows:
Sayhi ("Nicholas", "How is you today?");

The output of this function is "Hello nicholas,how is you today?". The named parameter in the definition in the function name and message are used as the two operands of the string concatenation, and the result is finally shown by the warning box.
A function in ECMAScript does not have to specify whether to return a value when it is defined. In fact, any function can implement the return value at any time by the return statement followed by the value to be returned. Take a look at the following example:
function sum (NUM1, num2) {
return NUM1 + num2;
}

The function of the sum () function is to add up to two values to return a result. We notice that, in addition to the return statement, there is no declaration that the function returns a value. The example code that calls this function is as follows:
var result = SUM (5, 10);
This function stops and exits immediately after executing the return statement . Therefore, any code that is behind the return statement will never be executed . For example:
function sum (NUM1, num2) {
return NUM1 + num2;
Alert ("Hello World"); Will never execute
}
In this example, the warning box is never displayed because the statement that calls the alert () function is after the return statement.
Of course, a function can also contain multiple return statements, as shown in the following example:
function diff (NUM1, num2) {
if (Num1 < num2) {
return NUM2-NUM1;
} else {
return num1-num2;
}
}

The diff () function defined in this example is used to calculate the difference of two values. If the first number is smaller than the second, the first number is reduced by the second number; otherwise, the second number is reduced by the first number. Each of the two branches in the code has its own return statement, which is used to perform the correct calculation.
In addition, the returnstatement can have no return value . In this case, the function returns a undefined value after it stops executing. This usage is generally used in cases where the function execution needs to be stopped prematurely without the return value . For example, in the following example, a warning box is not displayed:
function Sayhi (name, message) {
Return
Alert ("Hello" + name + "," + message); Will never call
}

Note: The recommended practice is either to have the function always return a value, or never to return a value. Otherwise, if the function sometimes returns a value, sometimes there is no return value, which can cause debugging code inconvenience.

Strict mode has some limitations on functions:
? The function cannot be named eval or arguments;
? The parameter cannot be named eval or arguments;
? Two named arguments cannot appear with the same name.
If this occurs, a syntax error is caused and the code cannot be executed.

Understanding Parameters

The arguments object is just like an array (it is not an instance of an array), because each element of it can be accessed using square brackets syntax (i.e. the first element is arguments[0], the second element is argumetns[1], and so on), using the length property to determine how many parameters are passed in. In the previous example, the first parameter of the Sayhi () function is named name, and the value of the parameter can be obtained by accessing Arguments[0]. Therefore, the function can also be overridden as follows, that is, the named parameter is not explicitly used:
function Sayhi () {
Alert ("Hello" + arguments[0] + "," + arguments[1]);
}

This rewritten function does not contain named arguments. Although the name and message identifiers are not used, the function is still functional. This fact illustrates an important feature of the ECMAScript function: named parameters are only convenient, but not required. In addition, in terms of named parameters, other languages may need to create a function signature beforehand, and future calls must be consistent with that signature. But in ECMAScript, without these rules, the parser does not validate named parameters.
by accessing the length property of a arguments object, you can tell how many arguments are passed to the function . The following function will output the number of arguments passed in each time it is called:
function Howmanyargs () {
alert (arguments.length);
}
Howmanyargs ("string", 45); 2
Howmanyargs (); 0
Howmanyargs (12); 1

Executing the above code will appear in turn 3 warning boxes, showing 2, 0, and 1, respectively. This shows that developers can take advantage of this to allow the function to receive arbitrary parameters and implement the appropriate functions separately. Take a look at the following example:
function Doadd () {
if (arguments.length = = 1) {
Alert (Arguments[0] + 10);
} else if (arguments.length = = 2) {
Alert (Arguments[0] + arguments[1]);
}
}
Doadd (10); 20
Doadd (30, 20); 50

The function Doadd () adds 10 to the parameter in the case of only one argument, and if it is two arguments, the argument is simply added and the result is returned. Therefore, Doadd (10) returns 20, while Doadd (30,20) returns 50. Although this feature is not a perfect overload, but also enough to compensate for the ECMAScript of this shortcoming.
Another important aspect related to parameters is that the arguments object can be used with named parameters, as shown in the following example:
function Doadd (NUM1, num2) {
if (arguments.length = = 1) {
Alert (NUM1 + 10);
} else if (arguments.length = = 2) {
Alert (Arguments[0] + num2);
}
}

In the rewritten Doadd () function, two named parameters are used with the arguments object. Because the value of NUM1 is the same as the value of arguments[0], they can be used interchangeably (of course, num2 and arguments[1] as well).
There's something more interesting about arguments's behavior. That is, its value is always kept in sync with the value of the corresponding named parameter.
For example:

function Doadd (NUM1, num2) {
ARGUMENTS[1] = 10;
Alert (Arguments[0] + num2);
}

Each execution of the Doadd () function overrides the second parameter, modifying the value of the second parameter to 10. Because the values in the arguments object are automatically reflected in the corresponding named arguments, modifying the arguments[1] also modifies the num2, resulting in their values becoming 10. However, this is not to say that reading these two values accesses the same memory space; their memory space is independent, but their values are synchronized. Also keep in mind that if only one parameter is passed in, the value set for ARGUMENTS[1] will not be reflected in the named parameter. This is because the length of the arguments object is determined by the number of arguments passed in, not by the number of named arguments when the function is defined.
The last thing to remember about parameters is that named parameters that do not pass values are automatically assigned the undefined value . This is the same as defining a variable without initializing it. For example, if you pass only one argument to the Doadd () function, the undefined value is saved in num2.
Strict mode makes some restrictions on how to use arguments objects. First, assignments like those in the previous example become invalid. That is, even if you set arguments[1] to 10,num2, the value is still undefined. Second, overriding the value of arguments results in a syntax error (the code will not execute).

No overloads
The ECMAScript function does not implement overloading as it is in the traditional sense. In other languages, such as Java, you can write two definitions for a function, as long as the two defined signatures (the type and number of parameters that are accepted) are different. As mentioned earlier, the ECMASCIRPT function has no signature because its arguments are represented by an array containing 0 or more values. Without a function signature, the real overload is impossible.
If two functions with the same name are defined in ECMAScript, the name belongs only to the post-defined function. Take a look at the following example:
function Addsomenumber (num) {
return num + 100;
}
function Addsomenumber (num) {
return num + 200;
}
var result = Addsomenumber (100); 300

Here, the function addsomenumber () is defined two times. The first version adds 100 to the parameter, while the second version adds 200 to the parameter. Since the function defined above is overwritten by the later functions, the returned result is 300 when the function is called in the last line of code.

As mentioned earlier, you can mimic the overloads of a method by examining the type and number of parameters in the incoming function and reacting differently.

Reading notes---Functions of advanced JavaScript programming

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.