In general, functions can be in javascript:
is assigned to a variable
Attributes assigned as objects
is passed as a parameter to another function
As the result of the function is returned
Create in literal quantities
Function Object
1.1 Creating functions
A not-so-long way to create JavaScript functions is to use the new operator as a function "constructor":
Copy Code code as follows:
var funcName = new Function ([Argname1, [... argnamen,]] body);
There can be any number of arguments in the argument list, followed by the function body, such as:
Copy Code code as follows:
var add = new Function ("X", "Y", "Return (X+y)");
Print (Add (2, 4));
The results will be printed:
6
But who can create a function in such a difficult way? If the function body is more complex, it takes a lot of effort to splice the string, so JavaScript provides a syntactic sugar, which creates a function by literal volume:
Copy Code code as follows:
function add (x, y) {
return x + y;
}
Or:
Copy Code code as follows:
var add = function (x, y) {
return x + y;
}
In fact, this kind of grammatical sugar makes it easier for traditional programmers to misunderstand, the function keyword invokes the function to new an object and passes the parameter table and function body to the function's constructor exactly.
Generally, an object is declared within the global scope (the scope will be described in detail in the next section). Just assigning a value to a property, such as the Add function in the previous example, simply adds a property to the global object, the property name is add, and the property's value is an object, which is the function (x, y) {return x+y;}, it's important to understand that this statement is syntactically:
Copy Code code as follows:
var str = "This is a string";
There are no two causes. is to add a new attribute dynamically to the global object, that's all.
To illustrate that a function, like any other object, is a running system that exists as a standalone object in JavaScript, we might as well look at this example:
Copy Code code as follows:
function P () {
Print ("Invoke p by ()");
}
P.id = "Func";
P.type = "function";
Print (p);
Print (p.id+ ":" +p.type);
Print (P ());
No mistake, p although the reference to an anonymous function (object), but can also have properties, exactly the same as other objects, the results of the operation are as follows:
function () {
Print ("Invoke p by ()");
}
Func:function
Invoke P by ()
1.2 Parameters of the function
In JavaScript, the parameters of a function are more interesting, for example, you can pass any number of arguments to a function, even if the function is declared without a formal parameter, such as:
Copy Code code 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 function Adprint accepts three formal arguments when declaring: The string to be printed, the length to be printed, and whether to convert to a case-and-write tag. But at the time of the call, we can pass the Adprint a parameter, two parameters, or three parameters (even more than 3, no relationship), and the results are as follows:
Hello, World
Hello
Hello
HELLO
In fact, when JavaScript handles the parameters of a function, unlike other compiled languages, the interpreter passes to the function an internal value similar to an array, called arguments, which 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, we can then adprint the function to process those undefined parameters, which can be exposed externally: we can handle any parameter.
We have another example to discuss this magical arguments:
Copy Code code 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));//"Lost" the magic number
Print (SUM ("new"));
function sum has no explicit formal parameters, and we can dynamically pass it to any number of arguments, so how do we refer to these parameters in the SUM function? Here we need to use this pseudo array of arguments, and the results are as follows:
150
108
Error:not a number exception
function scopes
The concept of scope is embodied in almost all major languages, and in JavaScript it is specific: variable scopes in JavaScript are valid in function bodies, without block scopes, in the Java language, we can define the subscript variable in the FOR loop block:
public void Method () {
for (int i = 0; i < obj1.length; i++) {
Do something here;
}
I at this time is undefined
for (int i = 0; i < obj2.length; i++) {
do something else;
}
}
And in javascript:
Copy Code code as follows:
function func () {
for (var i = 0; i < Array.Length; i++) {
Do something here.
}
At this time I still have a value, and i = = Array.Length
print (i);//i = = Array.Length;
}
A function of JavaScript is run within a local scope, and a function body running within a local scope can access variables and functions of its outer (possibly global scope). The scope of JavaScript is the lexical scope, and the so-called lexical scope is that its scope is defined at the time of definition (lexical analysis), not at the time of execution, as in the following example:
Copy Code code as follows:
var str = "global";
function Scopetest () {
Print (str);
var str = "local";
Print (str);
}
Scopetest ();
What is the result of the operation? Beginners are likely to come up with the answer:
Global
Local
and the correct result should be:
Undefined
Local
The first print (str) returns a undifined error because the scopetest variable str is previously accessed in the definition of the function, and then the STR variable is initialized. So why doesn't the function visit the external str variable at this time? This is because, at the end of lexical analysis, when constructing the scope chain, the var variable defined within the function is put into the chain, so str is visible within the entire function scopetest (from the first line of the function body to the last line). Because the STR variable itself is undefined, the program executes sequentially, the first line returns undefined, and the second behavior Str is assigned, so the third row of print (str) returns "Local".
function Context
In languages such as Java or C + +, methods (functions) can only be attached to objects and are not independent. In JavaScript, a function is also an object, not part of any other object, particularly important to understand, especially useful for understanding functional JavaScript, which is considered a first-class function in a functional programming language.
The context of a function can be varied, so that this in a function can also vary, a function can act as a method of an object, or as a method of another object, in short, the function itself is independent. You can modify the context of a function by using the call or Apply function on a function object:
Call and apply
Call and apply are often used to modify the context of a function, and the this pointer in a function is replaced by the first argument of call or apply, so let's take a look at the introduction of JavaScript and the example in JSON:
Define a person, the name is Jack
var jack = {
Name: "Jack",
Age:26
}
Define another person, named Abruzzi
var Abruzzi = {
Name: "Abruzzi",
Age:26
}
To define a global function object
function Printname () {
return this.name;
}
Set Printname context for Jack, this is Jack.
Print (Printname.call (Jack));
Set the Printname context to Abruzzi, 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 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 results obtained are:
Jack Sept.
John Abruzzi
The second parameter of apply is an array of the parameters that a function requires, and call needs to be separated by a comma (,) of several arguments.
Working with functions
As mentioned earlier, in JavaScript, functions can be
is assigned to a variable
Attributes assigned as objects
is passed as a parameter to another function
As the result of the function is returned
Let's take a look at these scenes separately:
Assign value to a variable:
Declares a function, accepts two arguments, returns its and
function add (x, y) {
return x + y;
}
var a = 0;
A = add;//to assign a function to a variable
var B = A (2, 3);//Call this new function a
Print (b);
This code prints "5" because after the assignment, the variable a refers to the function add, that is, the value of a is a function object (an executable block), so you can use a statement such as a (2, 3) to sum the operation.
Assign to properties of an object:
Copy Code code as follows:
var obj = {
ID: "Obj1"
}
Obj.func = add;//Property assigned to obj Object
Obj.func (2, 3);//Return 5
In fact, this example is essentially the same as the previous example, in the first example of a variable, which is actually a property of the global object (if it is represented as a Window object in the client environment). The second example is the Obj object, which is described separately because we rarely refer to the global object directly.
Passed as a parameter:
Second version of advanced print function
function AdPrint2 (str, handler) {
Print (Handler (str));
}
Converts a string to uppercase and returns
function up (str) {
return Str.touppercase ();
}
Converts a string to lowercase and returns
function Low (str) {
return Str.tolowercase ();
}
AdPrint2 ("Hello, World", up);
AdPrint2 ("Hello, World", low);
To run this fragment, you can get a result like this:
HELLO, World
Hello, world
It should be noted that the second parameter of the function AdPrint2, in fact, is a function that passes this handler function as a parameter, and can still call this function inside the adPrint2, which is useful in many places, especially when we want to handle some objects, However, there is no certainty as to what form to process, then the "processing" can be wrapped as an abstract granularity (i.e. function).
As the return value of the function:
Let's look at one of the simplest examples:
Copy Code code as follows:
function currying () {
return function () {
Print ("curring");
}
}
Function currying Returns an anonymous function that prints "curring", and a simple call to currying () results in the following:
Copy Code code as follows:
function () {
Print ("curring");
}
If you want to call this anonymous function returned by currying, you need this:
Currying () ();
The first bracket operation, which means the call to the currying itself, at which time the return value is a function, and the second bracket operator calls the return value, the result is this:
Currying