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 it is to declare a function in JavaScript.

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.

Alert (typeof fun1); // functionalert (typeof fun2); // undefinedalert (typeof fun3); // undefinedalert (typeof fun4); // functionalert (typeof fun5 ); // functionfunction 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?

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.

fun1(); // nthis["fun1"](); // nthis.fun1(); // nwindow["fun1"](); // nwindow.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?

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.

fun1(); //default

Firefox uses the statement in if as a fast execution and only compiles it during runtime. Therefore, the result is:

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

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.

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.

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

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.

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.

alert(typeof fun3); //functionalert(typeof fun4); //undefined

In IE

alert(typeof fun3); //functionalert(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.

VaR fun3 = function fun4 () {// declare a variable pointing to a non-Anonymous function expression} fun3 (); alert (typeof fun3); // functionalert (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

function fun1() {    alert("A");}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:

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.

VaR fun1 = function fun2 () {alert ("OK");} fun1 (); // okfun2 (); // 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.

var fun1 = function fun2() {    alert("OK");}fun1 = function() {    alert("fun1");}fun1(); //fun1fun2(); //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.

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:

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

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

$(function() {    $(":button").click(    function() {        for (var i = 0; i < 10; i++) {            var ol = $("<li>").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 - 1).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

$(function() {    $("div").click(    function() {        $("<div>").appendTo("body").css(        (function(e) {            var styleObj = {};            for (var item in e.style) {                if (e.style[item] != "") {                    styleObj[item] = e.style[item];                }            }            return styleObj;        } (this))        );    }    );});
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.