JavaScript Learning Notes (iv) Function functions Part _ Basics

Source: Internet
Author: User
Tags eval

A function is an event-driven or reusable block of code that executes when it is invoked.
Jscript supports two functions: one is a function within the language (such as Eval ()) and the other is created by itself.

A variable declared inside a JavaScript function (using VAR) is a local variable, so it can only be accessed within the function. (The scope of the variable is local).

You can use local variables with the same name in different functions, because only the function that declares the variable can recognize the variable.

How functions are called

1, Ordinary call: functionname (actual parameters ...)

2, by pointing to the function of the variable to call:

var myVar = function name;

MyVar (actual parameter ...);

Functions that return functions

1. When the function does not return a value explicitly, the value returned is "undefined".

2. When a function has a return value, the return value is what is returned.

We can do this by using the return statement to get the function back to the place where it was invoked.

When you use the return statement, the function stops executing and returns the specified value.

Function usually returns a unique value, the value may also be another function:

Copy Code code as follows:

<script type= "Text/javascript" >
var box = function () {
var a=1;
return function () {
Alert (a++)
}
}
Alert (Box ());//Eject "function () {alert (a++)}"
</script>

Here we just assign the return value to a variable, and then we can call it like a normal function:

Copy Code code as follows:

<script type= "Text/javascript" >
var box = function () {
var a=1;
return function () {
Alert (++a)
}
}
var newfunc = box ();
Newfunc ();//2
</script>

If you want the returned function to execute immediately, you can also use Box () () to execute the code.

ECMAScript the parameters of all functions are passed by value, which means that parameters are not passed by reference.

PS: If there is passing by reference, the variable in the function will be a global variable and can be accessed externally.

(1) value type: Numeric, Boolean, null, undefined.
(2) Reference type: object, array, function.

Reference type value: Refers to those objects stored in the heap memory, meaning that the variable is actually stored in a pointer, this pointer executes another location in memory, where the object is saved;
Create an anonymous function

Copy Code code as follows:

function () {
Return to ' Lee '; A separate anonymous function cannot be run, and cannot be invoked even if it can be run, because there is no name
}

The use of this anonymous function is very much in jquery. Declare an anonymous function directly and use it immediately. The advantage of using an anonymous function is that it saves you from defining a function that you don't want to use once, and without naming conflicts, there is no concept of namespaces in JS, so it's easy to have a function name conflict, once the naming conflict is final.

To execute an anonymous function by executing itself:

Copy Code code as follows:

Execute anonymous functions by self execution

<script type= "Text/javascript" >
(function () {//(anonymous function) (); First parenthesis put anonymous function, second parenthesis executes
Alert (' Lee ');
})();
</script>

Assigns the return value of the anonymous function self execution to the variable:

Copy Code code as follows:

Assign the return value of the anonymous function self execution to the variable

<script type= "Text/javascript" >
var box = (function () {
Alert (' Lee ');
})(); Pop-up "Lee";
alert (box); Pop-up undefined, if you write alert (box), then only a "Lee" pops up.
</script>

Self-executing parameters for anonymous functions:

Copy Code code as follows:

Self-executing the parameters of anonymous functions

<script type= "Text/javascript" >
(function (age) {
alert (age);
}) (100); Pop up 100
</script>

JavaScript to create dynamic functions:

JavaScript supports the creation of dynamic functions, which must be defined by Function objects (function is an object in JavaScript that is fixed, and the "F" of a function object must be capitalized, when it is a function). We know it is a keyword used when defining functions: Function Funname (x,y), when it is a function (when F is capitalized), we know it is an object in JavaScript.

Create a basic format for dynamic functions: var variable name = new function ("Parameter 1", "Parameter 2", "Parameter N", "execute statement");
Look at the following section of code:

Copy Code code 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 results of square (2,3) are: 5
</script>

Square is a dynamically created function, and each part of the parentheses behind the function object must be in a string form, meaning that all must be enclosed in quotation marks ("" or "").

This piece of code:

var square = new Function ("X", "Y", "var sum; sum = X+y;return sum;");
And the following code:

Copy Code code as follows:

function Square (x,y) {
var sum;
sum = x+y;
return sum;
}

is the same, but one is a dynamic function, the other is a static function.
Why do we have to divide the code into small pieces of code? , the advantage of dividing a string into separate strings is that we can change the function at any time by modifying some of the strings.

callback function

A callback is the calling procedure for a function. Let's begin by understanding the call process. Function A has a parameter, which is a function B, which executes function B when function A is done. Then the process is called a callback.

In fact, Chinese is also very good understanding: callback, callback, is called back to the meaning of the call. Function A is done in advance, then call function B later.

It must be clear here that function B is what you pass to function A as a parameter, then function B is called the callback function.

Most of the effect functions in jquery involve callback functions. jquery effect function
For example:

Copy Code code as follows:

<script type= "Text/javascript" >
$ ("div"). Show (1000,function () {
callback function
});
</script>

Here the callback function is replaced with an instance that can be:

Copy Code code as follows:

<script type= "Text/javascript" >
$ ("div"). Show (1000,function () {
Console.log ("Hello World")
});
</script>

Callback actually, when a function is done, the function that is being executed is the so-called callback function. What do you think? Very well understood ...

The difference between a method and a function

Copy Code code as follows:

var arr = [1,2,3,4,5]
var a = 12; Variables: the Free
Arr.a= 5; Attributes: Belong to an object
function Show ()//functions: Free
{
Alert (' a ');
}
Arr.fn = function ()//method: belongs to an object
{
Alert (' B ');
}

In fact, the method is a function, except that the method is the object to which it belongs.

As we know, binding a function to the Click event
Grammar:

$ (selector). Click (function)
Parameter description
Function Optional. Specify the function to run when the Click event occurs.
This form is often seen in jquery. It adds an event handler to the method by treating the function as an argument to the method.

JS Global function

A global function is not a concept with a built-in object's properties or methods. Global function It does not belong to any one of the built-in objects.
JavaScript contains the following 7 global functions to accomplish some of the most common features:

Escape (), eval (), Isfinite (), isNaN (), parsefloat (),
parseint (), unescape ().
Several functions of the function

Used as a class builder

Copy Code code as follows:

function class () {}
class.prototype={};
var item=new class ();

Use as closures

Copy Code code as follows:

(function () {
Independent scopes
})();

Called as a constructor function

The so-called constructor, is to generate a new object by using this function.

Copy Code code as follows:

<script type= "Text/javascript" >
function Test () {
This.x = 10;
}

var obj = new Test ();
alert (obj.x); Pop 10;
</script>

You can use the new operator to combine predefined constructors such as Object (), Date (), and function () to create and initialize an object. The powerful feature of object-oriented programming is the ability to define custom constructors to create custom objects that are used in scripts. A custom constructor is created so that an object with the defined property can be created. The following is an example of a custom function (note the use of this keyword).

Copy Code code as follows:

function Circle (Xpoint, Ypoint, radius) {
This.x = Xpoint; The x-coordinate of the center of the circle.
This.y = Ypoint; The y-coordinate of the center of the circle.
THIS.R = radius; The radius of the circle.
}

When the Circle constructor is invoked, the value of the center point and the radius of the circle are given (all of these elements are necessary to fully define a unique circular object). At the end of the Circle object contains three properties. Here's how to sample the Circle object.

var acircle = new Circle (5, 11, 99);
The advantage of using a constructor function is that it can receive some parameters when the object is created again.

Copy Code code 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 (' TRIGKIT4 ');//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 capitalize the first letter of the constructor function so that it differs significantly from the normal function.

The following two forms of definition function are equivalent.

Copy Code code as follows:

<script type= "Text/javascript" >
var test = function () {
Alert ("Hello World");
}
Alert (typeof (Test));//output function
</script>

A variable test is explicitly defined here, and his initial value is given to a function entity

Copy Code code as follows:

<script type= "Text/javascript" >
function Test () {
Alert ("Hello World");
}
Alert (typeof (Test));//output function
</script>

Take a look at the following form of defined function:

Copy Code code as follows:

<script type= "Text/javascript" >
function Test () {
Alert ("Hello World");
};
Test ();//actually output Hello, it's strange, isn't it?

function Test () {
Alert ("Hello");
};
Test ();//normal drop of Hello
</script>

Obviously, the first function doesn't work, it's weird, doesn't it? We know that the JavaScript parsing engine does not execute code one line at a time, but rather executes code for a period of time. In the analysis of the same program, the defined function statements are given precedence, so the first defined code logic is already overwritten by the second, so call the same function two times and only execute the second one.

function as a value

The function in JS is not only a syntax, but also a value. That is, you can assign a function to a variable, which is stored in the object's properties or in the element of an array, passing as a parameter into another function.
The name of the function is actually invisible, it is just the name of the variable, which refers to the function object

Copy Code code 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 properties, which are called methods when the function is called as an object's property.

Copy Code code as follows:

<script type= "Text/javascript" >
var obj = {square:function (x,y) {//Object Direct Quantity
return x*y;
}};
var ect = obj.square (2,3);
</script>

Prototype property

Each function contains the prototype attribute, which points to a reference to an object called a prototype object.
See: JavaScript Learning Notes (v) prototypes and prototype chains

Higher order functions

The higher order function here is not the higher order function in the high number, the so-called higher order function is the function of the operation function, it receives one or more functions as arguments, and returns the new function

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.