Note the following before getting started with javaScript: function section

Source: Internet
Author: User
In javaScript, a function is a very basic object. It is also very casual and can be defined at will. It is more casual to use. The following describes how casual a function is in javaScript [html] functionfun1 () {// declare a function} function () {... SyntaxHighlight

In javaScript, a function is a very basic object. It is also very casual and can be defined at will. It is more casual to use. The following describes how casual it is to declare a function in javaScript.

[Html]
Function fun1 () {// declare a function
 
}
 
Function () {// declare an anonymous function
 
}
 
Var fun2 = function () {// declare a variable pointing to an anonymous function expression
 
}
 
Var fun3 = function fun4 () {// declare a variable pointing to a non-Anonymous function expression
 
}
 
Function fun5 (){
Return function () {// returns an anonymous function
 
}
}

What are the differences between function and var? We will not discuss the profound issues. Let's look at the running results.
[Html]
Alert (typeof fun1); // function
Alert (typeof fun2); // undefined
Alert (typeof fun3); // undefined
Alert (typeof fun4); // function
Alert (typeof fun5); // function
 
 
Function fun1 () {// declare a function
 
}
 
Function () {// declare an anonymous function
 
}
 
Var fun2 = function () {// declare a variable pointing to an anonymous function expression
 
}
 
Var fun3 = function fun4 () {// declare a variable pointing to a non-Anonymous function expression
 
}
 
Function fun5 (){
Return function () {// returns an anonymous function
 
}
}

We can see that function takes precedence over var.
As we have said before about variables, a variable can be assigned multiple times. Can this be true for a function?
People who are used to writing code in static languages may be angry with the following code. What is this code?
[Html]
Function fun1 (){
Alert ("Y ");
}
 
Function fun1 (){
Alert ("N ");
}
But in fact, this code can be executed. The execution result implies that our function name will be automatically used as an attribute of the object. The function body is the attribute value.
[Html]
Fun1 (); // n
 
This ["fun1"] (); // n
This. fun1 (); // n
Window ["fun1"] (); // n
Window. fun1 (); // n

Now let's take a look at the two factors. The function is compiled before all code is executed, and the subsequent function will overwrite the previous function definition. Then, what is the following code executed?
[Html]
Var input = 5;
Switch (input ){
Case 10:
Function fun1 (){
Alert (10 );
}
Break;
Case 5:
Function fun1 (){
Alert (5 );
}
Break;
Default:
Function fun1 (){
Alert ("default ");
}
Break;
}

What is annoying is that in chrome and IE, the previous inference is that the function is compiled before all code is executed, and the subsequent function will overwrite the previous function definition result.
[Html]
Fun1 (); // default

FireFox uses the statement in if as a fast execution and only compiles it during runtime. Therefore, the result is:
[Html]
Fun1 (); // 5
To solve this problem, you need to dynamically allocate functions to execute them using function expressions to prevent the compiler from allocating functions before they are executed. For example

[Html]
Var input = 5;
Switch (input ){
Case 10:
Fun1 = function (){
Alert (10 );
}
Break;
Case 5:
Fun1 = function (){
Alert (5 );
}
Break;
Default:
Fun1 = function (){
Alert ("default ");
}
Break;
}

What is a function expression when it comes to function expressions? Simply put, the right side is a function expression.
[Html]
Var fun1 = function () {// function expression
 
}
 
Var fun1 = function fun2 () {// function expression
 
}
 
Var obj = {
Do: function () {// function expression
 
}
}
 
New function () {// function expression
 
}
 
Function fun3 (){
Return function () {// function expression
 
}
}
There are two other methods: In () and [], forgive me for reading it clearly. I used the Chinese [], and the code is OK.

[Html]
(Function (){});
[Function () {}];

Function expressions are compiled only when execution is the same as the values of general expressions. However, a non-Anonymous function expression is an exception.
[Html]
Var fun3 = function fun4 () {// declare a variable pointing to a non-Anonymous function expression
 
}

If the above Code does not have a specific meaning, please do not write it like this, because it may be unexpected.
[Html]
Alert (fun3 = fun4 );

The above result is beyond the idea of beginners in any case: false in IE Chinese, it is wrong in Chrome or FireFox
The reason for Chrome or FireFox is obvious, that is, fun4 is discarded immediately after being assigned a value.

[Html]
Alert (typeof fun3); // function
Alert (typeof fun4); // undefined

In IE
[Html]
Alert (typeof fun3); // function
Alert (typeof fun4); // function
This is an IE error, but we can know from the results that the name of the namefunction expression is invalid in the external scope. Even if it is as follows, you cannot execute fun3 www.2cto.com.
[Html]
Var fun3 = function fun4 () {// declare a variable pointing to a non-Anonymous function expression
 
}
 
Fun3 ();
 
Alert (typeof fun3); // function
Alert (typeof fun4); // undefined

Although IE is incorrect, IE discloses a message that a non-Anonymous function expression is assigned priority due to its name. Let's take a look at fun4 in the case of our top function definition declaration.
In this case, if you are not careful

[Html]
Function fun1 (){
Alert ("");
}
 
Var count = 2;
 
Var input = 10;
Switch (input ){
Case 5:
Function fun1 (){
Alert (5 );
}
Break;
Case 10:
If (count % 2 = 0 ){
Function fun1 (){
Alert ("odd ");
}
}
Else {
Function fun1 (){
Alert ("even ");
}
}
}
 
Fun1 ();

Will the execution of these codes be unexpected? Note that the above Code is different in different browsers. Let's look at the following code:
[Html]
Var fun1 = function (x ){
If (x <10 ){
Return function fun2 (){
Alert ("min ");
}
}
Return function fun2 (){
Alert ("max ");
}
}
 
Fun1 (4 )();
Fun1 (10 )();

Do you think that the execution result min has max in different browsers? Wrong, this time they are all expected. It indicates that return treats non-Anonymous function expressions as expressions rather than declarations.
So what are the problems with non-Anonymous function expressions?
Let's look at a demo.
[Html]
Var fun1 = function fun2 (){
Alert ("OK ");
}
 
Fun1 (); // OK
Fun2 (); // pop up OK in IE, error in Chrome and FireFox
Since we only support IE, we can continue to implement it on IE. To learn a language, do not be limited by the rules in the book. It is best to think a lot of unserious code, people with static language experience will be scared to death by the execution results of the following code.
[Html]
Var fun1 = function fun2 (){
Alert ("OK ");
}
 
Fun1 = function (){
Alert ("fun1 ");
}
 
Fun1 (); // fun1
Fun2 (); // OK

Fun1 and fun2 do not actually point to the same object or memory address. Therefore, if this is an IE bug, we are fortunate that Chrome and FireFox do not support non-Anonymous function expressions. God bless, in this way, do not write non-Anonymous function expressions as much as possible to avoid many problems. However, it is also said that non-Anonymous function expressions are useful in recursion. The following code tells us that anonymous function expressions can also be recursive.

A recursive factorial demo is used for an anonymous function.

[Html]
Alert (function (x ){
If (x> 1 ){
Return x * arguments. callee (-- x );
}
Else {
Return 1;
}
} (10); // 3628800

 


The above is a lot of things to tell you a key fact: function expressions can only be created in the code execution stage and do not exist in variable objects. To put it another common saying: function expressions exist only when they are executed. Otherwise, they exist when they do not exist.

In addition to the return and internal values, anonymous functions are often used for one-time execution of Self-executed functions. The following is a demo of anonymous function self-execution:
[Html]
(Function (){
Alert ("OK ");
})();
 
 
(Function (){
Alert ("OK ");
}());

The two methods above can be executed in all browsers. What do you like, as long as they are fixed? Some books recommend method 2. I don't know why, it is very casual for me.
Anonymous functions can also pass parameters.
[Html]
(Function (x ){
X --;
Alert (x );
} (10 ));

Anonymous functions are often very useful. We can pass anonymous functions as a parameter. Sometimes, what we pass is actually the function itself, and sometimes what we pass is the result of the function, if it is the result of a function, the function's self-calling will be very cool.

Let's take a look at the passing function. The following code will generate a set of li elements, and the background color is based on the background color of the previous li, which looks like a gradient area. Of course, you do not have to do this to draw a gradient area.

[Html]
$ (
Function (){
$ (": Button"). click (
Function (){
For (var I = 0; I <10; I ++ ){
Var ol = $ ("

  • ").Css ({width: 30, height: 30 }).
    AddClass ("left ").
    AppendTo ("ol ");
    Ol.css ("backgroundColor ",
    Function (index, value ){
    Index = $ ("ol> li"). index (this );
    Var r, g, B = 0, colorValue = "";
    If (index = 0 ){
    R = parseInt (Math. random () * 256 );
    G = parseInt (Math. random () * 256 );
    B = parseInt (Math. random () * 256 );
    }
    Else {
    ColorValue = $ ("ol> li"). eq (index-12.16.css ("backgroundColor ").
    ToString (). replace ("rgb (", ""). replace (")","")
    R = parseInt (colorValue. split (",") [0]);
    G = parseInt (colorValue. split (",") [1]);
    B = parseInt (colorValue. split (",") [2]) + 5;
    }
    Return "rgb (" + r + "," + g + "," + B + ")";
    }
    );
    }
    }
    );
    }
    );

    Let's look at another example. The self-tuning of anonymous functions is useful for passing parameters. When we click a div, I create a new div. The div style completely copies the clicked div style, note that an anonymous self-called function is passed in my css function. This function returns an object
    [Javascript]
    $ (
    Function (){
    $ ("Div"). click (
    Function (){
    $ (""). AppendTo ("body" example .css (
    (Function (e ){
    Var styleObj = {};
    For (var item in e. style ){
    If (e. style [item]! = ""){
    StyleObj [item] = e. style [item];
    }
    }
    Return styleObj;
    } (This ))
    );
    }
    );
    }
    );

    From the column of shyleoking

  • 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.