Basic functions for getting started with JavaScript

Source: Internet
Author: User

In general, functions in JavaScript can:

◆ Assigned to a variable

◆ Attributes assigned as objects

◆ Passed into other functions as parameters

◆ Returned as a function result

◆ Create with words

Function object

1.1 create a function

A method of creating JavaScript Functions (almost nobody uses) is to use the new operator to act on the Function "Constructor ":

Copy codeThe Code is as follows: var funcName = new Function ([argname1, [... argnameN,] body );
The parameter list can contain any number of parameters followed by the function body, for example:

Copy codeThe Code is as follows: var add = new Function ("x", "y", "return (x + y )");
Print (add (2, 4 ));
The result is printed:

6

But who will create a function in such a difficult way? If the function body is complex, it takes a lot of effort to splice this String. Therefore, JavaScript provides a syntax sugar, that is, to create a function using the literal volume:

Copy codeThe Code is as follows: function add (x, y ){
Return x + y;
}
Or:

Copy codeThe Code is as follows: var add = function (x, y ){
Return x + y;
}
In fact, such syntactic sugar is more likely to cause misunderstandings of programmers in the traditional field. The function keyword will call the Function to create a new object, and pass the parameter table and Function body to the Function constructor accurately.

Generally, an object is declared in the global scope (the scope will be detailed in the next section), but it is only a value to an attribute, such as the add function in the previous example, in fact, only an attribute is added to the global object. The attribute name is add, and the attribute value is an object, that is, function (x, y) {return x + y ;}, it is important to understand this point. The syntax of this statement is as follows:

Copy codeThe Code is as follows: var str = "This is a string ";
No problem. They all Add a new attribute to the global object dynamically.

To demonstrate that functions, like other objects, exist in the JavaScript operating system as an independent object, let's look at this example:

Copy codeThe Code is as follows: function p (){
Print ("invoke p ()");
}

P. id = "func ";
P. type = "function ";

Print (p );
Print (p. id + ":" + p. type );
Print (p ());
No error. Although p references an anonymous function (object), it can also have attributes, just like other objects. The running result is as follows:

Function (){
Print ("invoke p ()");
}
Func: function
Invoke p ()

1.2 function parameters

In JavaScript, function parameters are interesting. For example, you can pass any number of parameters to a function, even if the function is declared with no formal parameters, for example:

Copy codeThe Code is as follows: function adPrint (str, len, option ){
Var s = str | "default ";
Var l = len | s. length;
Var o = option | "I ";

S = s. substring (0, l );
Switch (o ){
Case "u ":
S = s. toUpperCase ();
Break;
Case "l ":
S = s. toLowerCase ();
Break;
Default:
Break;
}

Print (s );
}

AdPrint ("Hello, world ");
AdPrint ("Hello, world", 5 );
AdPrint ("Hello, world", 5, "l"); // lower case
AdPrint ("Hello, world", 5, "u"); // upper case
The adPrint function accepts three form parameters when declaring: the string to be printed, the length to be printed, and whether to convert it to a case-sensitive flag. But when calling, we can pass a parameter, two parameters, or three parameters to adPrint in order (or even more than three parameters can be passed to it, it does not matter ), the running result is as follows:

Hello, world
Hello
Hello
HELLO

In fact, JavaScript is different from other compiled languages when processing function parameters. What the interpreter passes to the function is an internal value similar to an array, called arguments, this is initialized when the function object is generated. For example, when we pass a parameter to adPrint, the other two parameters are undefined. in this way, the adPrint function can process undefined parameters internally and make them public to the outside: we can process arbitrary parameters.

Let's use another example to discuss this magical arguments:

Copy codeThe Code is as follows: function sum (){
Var result = 0;
For (var I = 0, len = arguments. length; I <len; I ++ ){
Var current = arguments [I];
If (isNaN (current )){
Throw new Error ("not a number exception ");
} Else {
Result + = current;
}
}

Return result;
}

Print (sum (10, 20, 30, 40, 50 ));
Print (sum (4, 8, 15, 16, 23, 42); // the magic number on Lost
Print (sum ("new "));
The sum function does not have explicit parameters, but we can dynamically pass them to any number of parameters. How can we reference these parameters in the sum function? Here, the pseudo array arguments is used. The running result is as follows:

150
108
Error: not a number exception

Function Scope

The concept of scope is embodied in almost all mainstream languages. In JavaScript, it has its own particularity: The variable scope in JavaScript is effective in the function body, but has no block scope, in Java, we can define the subscript variable in the for loop block as follows:

Public void method (){
For (int I = 0; I <obj1.length; I ++ ){
// Do something here;
}
// At this time, I is undefined.
For (int I = 0; I <obj2.length; I ++ ){
// Do something else;
}
}
In JavaScript:

Copy codeThe Code is as follows: function func (){
For (var I = 0; I <array. length; I ++ ){
// Do something here.
}
// At this time, I still has a value, and I = array. length
Print (I); // I = array. length;
}
JavaScript Functions run in a local scope. The function bodies running in a local scope can access the variables and functions in its outer (possibly global. The JavaScript scope is the lexical scope. The so-called lexical scope means that its scope is determined when it is defined (during lexical analysis), rather than when it is executed, as shown in the following example:

Copy codeThe Code is as follows: var str = "global ";
Function scopeTest (){
Print (str );
Var str = "local ";
Print (str );
}

ScopeTest ();
What is the running result? Beginners may come up with the following answer:

Global
Local

The correct result should be:

Undefined
Local

Because in the definition of the function scopeTest, the undeclared variable str is accessed in advance before initialization of the str variable, so the first print (str) will return the undifined error. Why does the function not access the external str variable at this time? This is because when the lexical analysis ends and the scope chain is constructed, the var variable defined in the function is put into the chain, therefore, str is visible in the whole function scopeTest (from the first row to the last row of the function body). Because the str variable itself is undefined, the program is executed sequentially, to the first line, the returned value is undefined, and the second row is assigned a value, so the print (str) of the third row will return "local ".

Function Context

In Java or C/C ++, methods (functions) can only be attached to objects and are not independent. In JavaScript, functions are also an object and are not part of any other object. Understanding this is particularly important, especially for understanding functional JavaScript, in functional programming languages, functions are considered to be first-class.

The context of a function can be changed. Therefore, this in a function can also be changed. A function can be used as an object method or another object method. In short, functions are independent. You can use the call or apply Function on the Function object to modify the context of the Function:

Call and apply

Call and apply are usually used to modify the context of the function. The this pointer in the function will be replaced with the first parameter of call or apply. Let's take a look at the object of getting started with JavaScript and the example in JSON:

// Define a person named jack
Var jack = {
Name: "jack ",
Age: 26
}

// Define another person named abruzzi
Var abruzzi = {
Name: "abruzzi ",
Age: 26
}

// Define a global function object
Function printName (){
Return this. name;
}

// Set the context of printName to jack. In this case, this is jack.
Print (printName. call (jack ));
// Set the context of printName to abruzzi. In this case, this is abruzzi.
Print (printName. call (abruzzi ));

Print (printName. apply (jack ));
Print (printName. apply (abruzzi ));
When there is only one parameter, call and apply are used in the same way. If there are multiple parameters:

SetName. apply (jack, ["Jack Sept."]);
Print (printName. apply (jack ));

SetName. call (abruzzi, "John Abruzzi ");
Print (printName. call (abruzzi ));
The result is as follows:

Jack Sept.
John Abruzzi
The second parameter of apply is an array composed of parameters required by a function, while call requires several parameters separated by commas.

Use Functions

As mentioned above, in JavaScript, the function can

◆ Assigned to a variable

◆ Attributes assigned as objects

◆ Passed into other functions as parameters

◆ Returned as a function result

Let's take a look at these scenarios:

Assign a value to a variable:

// Declare a function, accept two parameters, and return its sum
Function add (x, y ){
Return x + y;
}

Var a = 0;
A = add; // assign a function to a variable
Var B = a (2, 3); // call this new function
Print (B );
This code will print "5", because after the value is assigned, variable a references the function add, that is, the value of a is a function object (an executable code block ), therefore, you can use a (2, 3) statement to perform the sum operation.

Attribute assigned to an object:

Copy codeThe Code is as follows: var obj = {
Id: "obj1"
}

Obj. func = add; // assign a value to the property of the obj object.
Obj. func (2, 3); // return 5
In fact, this example is essentially the same as the previous example. The a variable in the first example is actually a Global Object (if it is expressed as a window object in the client environment). The second example is an obj object. Since we seldom directly reference a global object, it is described separately.

Pass as a parameter:

// The second version of the advanced printing function
Function adPrint2 (str, handler ){
Print (handler (str ));
}

// Convert the string to uppercase and return
Function up (str ){
Return str. toUpperCase ();
}

// Convert the string to lowercase and return
Function low (str ){
Return str. toLowerCase ();
}

AdPrint2 ("Hello, world", up );
AdPrint2 ("Hello, world", low );
Run this clip to obtain the following result:

HELLO, WORLD
Hello, world

It should be noted that the second parameter of the adPrint2 function is actually a function, which is passed in as a parameter and can still be called within adPrint2, this feature is useful in many places, especially when we want to process some objects, but are not sure what form to process, you can use the "Processing Method" as an abstract granularity for packaging (that is, a function ).

Return Value of the function:

Let's take a look at the simplest example:

Copy codeThe Code is as follows: function currying (){
Return function (){
Print ("curring ");
}
}
The currying function returns an anonymous function. The anonymous function prints "curring". The following result is returned when you call currying:

Copy codeThe Code is as follows: function (){
Print ("curring ");
}
If you want to call the anonymous function returned by currying, You need:

Currying ()();
The first parenthesis operation indicates that the currying itself is called, and the return value is a function. The second bracket operator calls this return value, and the result is as follows:

Currying

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.