Several ways to define JavaScript functions

Source: Internet
Author: User

Origin

JavaScript is more casual than other programming languages, so the JavaScript code is filled with all kinds of exotic writing, sometimes mirrors, and of course, the ability to understand the various types of writing is also a further understanding of JavaScript language features, then he has several ways of writing it?

(function () {...}) ()

Or

(function () {...} () )

The first thing to understand is two points of knowledge

JS in the function is a reference type, function General execution Way: function name + ();

The following example helps you understand the reference type

var a = function (x, y) {    console.log (× + y);}; var  b = a;a;//b,a points to the same function object//b re-assignment b = function (x, y) {    

Several ways to define a function

JS function has common functions, constructors, anonymous functions, the definition of three kinds of ways, that is, function declaration mode (Functions declaration, abbreviation as FD), function expressions (functions expression, Abbreviation as FE), the Function object Way (the way the object defines the function, the preceding argument is the parameter of the function, and finally the function body.) But you need to parse the incoming string parameter, resulting in two parsing, so this is not recommended to define the function.

1. Function declaration method

No error is made, but the JavaScript engine only parses the function declaration, ignoring the following parentheses, and the function declaration will not be called Functions FnName () {    alert (' Hello World ');} ();//Can execute alert (sum); function sum (x, y) {return x + y;}

2. Function Expression method

This code will error alert (sum), var sum = function (x, y) {   return x + y;} The function expression is appended with parentheses, and the function var show=function () {    alert (' Hello world ') can be called immediately when the JavaScript engine resolves to this point;} ();

3. Function Object method

var sum = new Function (' value1 ', ' value2 ', ' return value1 + value2 ');

You can write this when you write recursion.

If the sum is renamed, or re-assigned, by using sum (x-1) + sum (x-2), the resulting bugvar sum = function fsum (x) {    if (x<=2)        return 1;    else        return Fsum (x-1) + fsum (x-2);}; Alert (SUM (5));

4. Anonymous function

Declaring a function using the functions keyword, but not naming the function, so called anonymous functions, anonymous functions are function expressions , anonymous functions have many functions, assigning a variable to create a function, assigning an event to an event handler or creating a closure, etc.

function () {}

Difference

1, FD is in the construction function execution context will be computed and as a property of activation object is referenced, so there is declaration hoisting phenomenon. Fe is computed in the runtime of the function and is not referenced as a property of the activation object, which means that FD is promoted by the parser through the function declaration, which is the functions declaration The hoisting is placed at the top of the original code, so it works even if you call the function before the function.

2, but the function expression way in addition to cannot be called before the Declaration, as the function declaration way

3, Function object method can intuitively understand "function is object, function name is pointer" This concept, but it will cause the parser two parse, once is ordinary ECMAScript code, once is parse in the function constructor function of the string, will affect the JS engine performance

4, the function expression can be called immediately after the function, function declaration can not

Execute function expression immediately

When we use JavaScript, we often see a function call like this

(function () {     console.log ("Test");}) ();

Or

(function () {     console.log ("Test");} ());

like jquery .

(Function (window, undefined) {    //code here}) (window);

There are two ways to address this .

"Self-executing anonymous function" (self-executing anonymous function), "Immediate execution of functional expressions" (immediately-invoked functions expression, hereinafter referred to as Iife)

There are some wonderful ways to define

If itself is expression, then there is no need to do any processing var i = function () {return 10;} (), True && function () {/* code */} (); 0, function () {/* code */} ();//If you do not care about the return value, you can do so!function () {/* code */} (); ~function () {/* code */} ();-function () {/* code */} (); +function () {/* code */} ();//There is a more exotic way, but do not know the performance, from the new function () {/* code */}new function () {/* code */} ()

Why do you want to use an immediate function expression

1, the scope of the simulation block

As is known to all, JavaScript does not have block scopes (blocks) in C or Java, only function scopes, which can easily overwrite objects or variables when multiple libraries are called simultaneously.

Liba.js

var num = 1;//code ....

Libb.js

var num = 2;//code ....

If both references and two libraries in the page are liba.js bound to cause the variable to liba.js num be overwritten, the problem can be solved by Iife:

Liba.js

(function () {    var num = 1;    Code ....}) ();

Libb.js

(function () {    var num = 2;    Code ....}) ();

2. Resolving closure conflicts

Closures (closure) is a language feature of JavaScript, which simply means that functions defined inside the function can hold the execution environment of the outer function, even if the outer function has been executed, this is not described in detail here, it is interesting to Google itself. We're only here to cite one of the most common problems caused by closures.

var f1 = function () {    var res = [];    var fun = null;    for (var i = 0; i <, i++) {Fun        = function () {console.log (i);};/ /Generate Closure        Res.push (fun);    }    return res;} Outputs 10 10 Instead of the expected 0 1 2 3 4 5 6 7 8 9var res = F1 (); for (var i = 0; i < res.length; i++) {    res[i] ();}

Modified to:

var f1 = function () {    var res = [];    for (var i = 0; i < i++) {        //Add a Iife        (function (index) {Fun            = function () {console.log (index);};            Res.push (fun);        }) (i);    }    return res;} The output is 0 1 2 3 4 5 6 7 8 9var res = F1 (); for (var i = 0; i < res.length; i++) {    res[i] ();}

can refer to http://segmentfault.com/q/1010000003490094

3, Analog single case

In JavaScript oop, we can do this through Iife, as follows

var counter = (function () {    var i = 0;     return {        get:function () {            return i;        },        Set:function (val) {            i = val;        },        increment: function () {            return ++i;}}    ;} ()); Counter.get (); 0counter.set (3); counter.increment (); 4counter.increment (); 5

Reference:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/#iife
Http://blog.coolaj86.com/articles/how-and-why-auto-executing-function.html
Http://stackoverflow.com/questions/592396/what-is-the-purpose-of-a-self-executing-function-in-javascript
Http://www.cnblogs.com/TomXu/archive/2011/12/31/2289423.html
Https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function

Several ways to define JavaScript functions

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.