Javascript learning notes (4) function part, learning notes function
A function is an event-driven or reusable code block that is executed when it is called.
Jscript supports two types of functions: one is internal functions (such as eval (), and the other is self-created.
The variable declared inside the JavaScript function (using var) is a local variable, so it can only be accessed inside the function. (The scope of this variable is local ).
You can use local variables with the same name in different functions, because only functions that have declared the variable can recognize the variable.
Function call Method
1. Common call: functionName (actual parameter ...)
2. Call the function by pointing to the function variable:
Var myVar = function name;
MyVar (actual parameter ...);
Return Function
1. When the function does not return a specific value, the returned value is "undefined ".
2. When a function returns a value, the return value is returned.
We can use the return statement to return the function to the place where it is called.
When the return statement is used, the function stops execution and returns the specified value.
A function usually returns a unique value, which may be another function:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var box = function (){
Var a = 1;
Return function (){
Alert (a ++)
}
}
Alert (box (); // the pop-up "function () {alert (a ++ )}"
</Script>
Here, we only need to assign the return value to a variable, and then we can call it like a common function:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var box = function (){
Var a = 1;
Return function (){
Alert (++)
}
}
Var newFunc = box ();
NewFunc (); // 2
</Script>
If you want the returned function to be executed immediately, you can also use box () to execute this code.
ECMAScript all function parameters are passed by value. The implication is that the parameters are not passed by reference.
PS: if there is a pass by reference, the variable in the function will be a global variable and can be accessed externally.
(1) Value Type: numerical value, Boolean value, null, undefined.
(2) reference type: object, array, and function.
Reference Type value: refers to the objects stored in the heap memory. It means that the objects stored in the variable are actually just a pointer, and this pointer is executed in another location in the memory, stores objects at this location;
Create an anonymous Function
Copy codeThe Code is as follows:
Function (){
Return 'lil'; // a separate anonymous function cannot be run. Even if it can be run, it cannot be called because it has no name.
}
This type of anonymous function is widely used in JQuery. Directly declare an anonymous function and use it immediately. The advantage of using an anonymous function is that you do not need to define a function that is not used once, and there is no naming conflict. js does not have a namespace concept, so it is easy to conflict function names, in case of any name conflict, the last statement shall prevail.
Execute anonymous functions through self-execution:
Copy codeThe Code is as follows:
// Execute anonymous functions through self-execution
<Script type = "text/javascript">
(Function () {// (anonymous function) (); the first parentheses are anonymous functions, and the second parentheses are executed.
Alert ('lil ');
})();
</Script>
Assign the returned value of the anonymous function self-execution to the variable:
Copy codeThe Code is as follows:
// Assign the returned value of anonymous function self-execution to the variable
<Script type = "text/javascript">
Var box = (function (){
Alert ('lil ');
}) (); // Pop up "Lee ";
Alert (box); // The undefined prompt is displayed. If you write alert (box (), only one "Lee" is displayed"
</Script>
Passing parameters for self-executed anonymous functions:
Copy codeThe Code is as follows:
// PASS Parameters for self-executed anonymous Functions
<Script type = "text/javascript">
(Function (age ){
Alert (age );
}) (100); // 100 is displayed.
</Script>
Create dynamic functions using javascript:
JavaScript supports the creation of dynamic functions. Dynamic functions must be defined using Function objects. (a Function is an object in javascript and remains unchanged. It specifies that the "F" of Function objects must be capitalized, when it is a function, we know that it is a keyword used when defining a function: Function funName (x, y), when it is a function (F in upper case ), we know it is an object in javascript)
Basic Format for creating a dynamic Function: var variable name = new Function ("parameter 1", "parameter 2", "parameter n", "execution statement ");
See the following code:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var square = new Function ("x", "y", "var sum; sum = x + y; return sum ;");
The result of alert ("square (2, 3) is:" + square (2, 3); // The result of square (2, 3) is: 5
</Script>
Square is a dynamically created Function. Each part of the content in the brackets behind the Function object must be in the string format, that is, it must be enclosed by quotation marks ("" or '').
This code:
Var square = new Function ("x", "y", "var sum; sum = x + y; return sum ;");
And the following code:
Copy codeThe Code is as follows:
Function square (x, y ){
Var sum;
Sum = x + y;
Return sum;
}
It is the same, but one is a dynamic function and the other is a static function.
Why should we split the code into a small segment of code ?, The advantage of dividing a string into several independent strings is that we can modify some of the strings to change the function at any time.
Callback Function
Callback is a function call process. Let's start by understanding the call process. Function a has a parameter, which is function B. function B is executed after function a is executed. This process is called callback.
In fact, the Chinese language is also well understood: callback, callback, is the meaning of the call back. Function a is finished beforehand, and then function B is called.
It must be clear that function B is passed to function a as a parameter, so function B is called a callback function.
In jquery, most of the effect functions involve the callback function. Jquery effect Functions
For example:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ ("Div"). show (1000, function (){
// Callback function
});
</Script>
Here, the callback function can be changed to an instance:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
$ ("Div"). show (1000, function (){
Console. log ("hello world ")
});
</Script>
The Callback function is actually called the callback function after a function is executed. How is it? Good understanding ......
Differences between methods and functions
Copy codeThe Code is as follows:
Var arr = [1, 2, 4, 5]
Var a = 12; // variable: free
Arr. a = 5; // attribute: belongs to an object
Function show () // function: free
{
Alert ('A ');
}
Arr. fn = function () // method: belongs to an object
{
Alert ('B ');
}
Actually, the method is a function, but the method has an object.
We are familiar with binding functions to click events.
Syntax:
$ (Selector). click (function)
Parameter description
Function is optional. Specifies the function that runs when a click event occurs.
This form is often seen in jquery. It uses function as a parameter of this method and adds an event processing function to this method.
Js global functions
The attributes or methods of global functions and built-in objects are not a concept. A global function does not belong to any built-in object.
JavaScript contains the following seven global functions for common functions:
Escape (), eval (), isFinite (), isNaN (), parseFloat (),
ParseInt (), unescape ().
Functions
Used as a class Constructor
Copy codeThe Code is as follows:
Function class (){}
Class. prototype = {};
Var item = new class ();
Used as a closure
Copy codeThe Code is as follows:
(Function (){
// Independent Scope
})();
Called as a constructor
The so-called constructor generates a new object through this function ).
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
This. x = 10;
}
Var obj = new test ();
Alert (obj. x); // 10 is displayed;
</Script>
You can use the new operator to create and initialize an Object with predefined constructors such as Object (), Date (), and Function. Object-Oriented Programming its powerful feature is the ability to define custom constructor to create custom objects used in scripts. A user-defined constructor is created to create objects with defined attributes. The following is an example of a user-defined function (note the use of this keyword ).
Copy codeThe Code is as follows:
Function Circle (xPoint, yPoint, radius ){
This. x = xPoint; // The x coordinate of the center.
This. y = yPoint; // y coordinate of the center.
This. r = radius; // the radius of the circle.
}
When the Circle constructor is called, the value of the center point and the Circle radius are given (all these elements are required to completely define a unique Circle object ). At the end, the Circle object contains three attributes. The following describes how to use a Circle object.
Var aCircle = new Circle (5, 11, 99 );
The advantage of using the constructor function is that it can receive some parameters when creating an object.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function Test (name ){
This. occupation = "coder ";
This. name = name;
This. whoAreYou = function (){
Return "I'm" + this. name + "and I'm a" + this. occupation;
}
}
Var obj = new Test ('trigger4'); // use the same constructor to create different objects
Var obj2 = new Test ('student ');
Obj. whoAreYou (); // "I'm trigkit4 and I'm a corder"
Obj2.whoAreYou (); // "I'm student and I'm a corder"
</Script>
By convention, we should capital the first letter of the constructor function to distinguish it from a common function.
The following two forms of function definition are equivalent.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var test = function (){
Alert ("Hello World ");
}
Alert (typeof (test); // output function
</Script>
A variable test is defined here, and its initial value is assigned a function entity.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
Alert ("Hello World ");
}
Alert (typeof (test); // output function
</Script>
Let's look at the following definition function form:
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function test (){
Alert ("Hello World ");
};
Test (); // The output is Hello. Isn't it strange?
Function test (){
Alert ("Hello ");
};
Test (); // Hello is output normally.
</Script>
Obviously, the first function does not work. Isn't it strange? As we know, the javascript parsing engine does not execute code one line at a time, but executes code in a segment. During the analysis and execution of the same program, the defined function statement is executed first, so the first defined code logic is overwritten by the second one. Therefore, the same function is called twice, only the second one will be executed.
Function as Value
In JavaScript, a function is not only a syntax but also a value. That is to say, you can assign a function to a variable and store it in the attributes of an object or an array element as a parameter to pass in to another function.
The function name is actually invisible. It is only the name of the variable. This variable refers to the function object.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Function square (x, y ){
Return x * y;
}
Var s = square; // s and square refer to the same function.
Square (2, 3); // 6
S (2, 4); // 8
</Script>
In addition to assigning a function to a variable, you can also assign a function to an object's attribute. When a function is called as an object's attribute, a function is called a method.
Copy codeThe Code is as follows:
<Script type = "text/javascript">
Var obj = {square: function (x, y) {// number of objects directly
Return x * y;
}};
Var ect = obj. square (2, 3 );
</Script>
Prototype attributes
Each function contains the prototype attribute, which points to an object reference. This object is called a prototype object.
For details, see javascript Study Notes (5) prototype and prototype chain.
High-order functions
The higher-order function here is not the Higher-Order Function in the higher number. The higher-order function is the function that operates the function. It receives one or more functions as parameters and returns new functions.
In javascript, functions are the same as functions, and new Object () functions are the same.
1 function is a function.
2. In JS, only function functions are incorrect.
3
<Body>
<Script type = "text/javascript">
Var value = new Object (); // defines value as an instance in a class.
Value. add = new Function ("a", "B", "return a + B"); // add is a method in value, and its value is return a + B, that is, the sum of a and B. Should a and B be variables? How can I write it like this? --I think this is an error.
Var result value. add (); // The result variable is defined here. It may be var result = value. add (), and it seems wrong...
Document. write (resulf); // output the result. Here it should be document. write (result );
</Script>
</Body>
What is the above Object? There is no such struct... Define it by yourself...
It's easy to write, and there's no need to write that... If no class definition is available, it will be messy ....
<Body>
<Script type = "text/javascript">
Function add (int a, int B) {return a + B ;}
Var value;
Value = add (18,19 );
Document. write (result );
</Script>
</Body>
That's OK.
Function () {function name ();} in javascript
What does a function call another function? That is, this function calls another function. Function Definition Note: unknown functions will not be called if they are not executed immediately!