JavaScript function Patterns and examples _ basics

Source: Internet
Author: User
Tags closure event listener function definition

The role of JavaScript design patterns is to improve the reusability and readability of your code, making it easier to maintain and extend your code

In JavaScript, a function is a class of objects, which means that he can pass as arguments to other functions, and functions can also provide scopes.

syntax for creating functions

named function expression

name function Expression
var add = function Add (a,b) {return
 a+b;
};

var foo = function bar () {
 Console.log (foo = = bar);
Foo ();//true

Visible, they refer to the same function, but this is only valid in the body of the function.

var foo = function bar () {};
Console.log (foo = = bar);//referenceerror:bar is not defined

However, you cannot call the function by calling bar ().

var foo = (function bar () {
 Console.log (foo = = bar);
}) ();//false

function expression

Also known as the anonymous function
var add = function (a,b) {return
 a+b;
};

The value assigned to the variable add is the function definition itself. In this way, add becomes a function that can be invoked anywhere.

Declaration of functions

function foo () {
 //code
here}//No semicolon is required here

In a trailing semicolon, a function expression should always use a semicolon, and the declaration of a function does not require a semicolon to end.

The difference between a declarative function and a function expression is that in the precompiled period of JS, the declarative function is extracted first, and then the JS code is executed sequentially:

Console.log (F1);//[FUNCTION:F1]
Console.log (F2);//undefined,javascript is not a complete sequential interpretation of the execution, but a "precompiled" of JavaScript before it is interpreted, and a defined function is given precedence during precompilation

Function F1 () {
 console.log ("I am F1");
}
var F2 = function () {
 console.log ("I am F2");

Since the declaration function is done in the global scope construct, declaring the function is a property of the Window object, which explains why we declare the function to be the end of the Window object, regardless of where we declare the function.

Any anonymous function in the JavaScript language belongs to the Window object. When the anonymous function is defined, it returns its own memory address, and if a variable at this time receives the memory address, the anonymous function can be used in the program, because the anonymous function is also defined and assigned when the global execution environment is constructed, so the this point of the anonymous function is also a Window object

var F2 = function () {
 console.log ("I am F2");
Console.log (F2 ());//i am F2

(function () {
 Console.log (this = = window);//true
}) ();

function declarations and expressions

Elevation of functions (hoisting)

The behavior of a function declaration is not the same as a named function expression, which differs in elevation (hoisting) behavior by looking at the following example:

<script type= "Text/javascript" >
 //Global functions Function
 foo () {alert ("Global Foo!");}
 function bar () {alert (' Global Bar ');}

 function hoist () {
  console.log (typeof foo);//function
  Console.log (typeof bar);//undefined

  foo ();// Local Foo!
  Bar ();//typeerror: ' Undefined ' is not a function 

  //variable foo as well as implemented by promoted
  function foo () {
   alert (' local foo! ');
  }

  Only the variable bar is promoted, the function implementation part is not promoted
  var bar = function () {
   alert (' local bar! ');}
 Hoist (); 
</script>

For all variables, no matter where the function body is declared, it is promoted internally to the top of the function. This is true for functions, because functions are simply objects assigned to variables.

Ascension, as the name suggests, is the following things mentioned above. In JS, it is to elevate the definition in the following (variable or function) to the previous definition. As you can see from the example above, the Foo and bar inside the function hoist are moved to the top, overwriting the global Foo and bar functions. The difference between a local function bar and Foo is that Foo is promoted to the top and works, and the definition of bar () is not promoted, only its declarations are elevated, so when the bar () is executed, the result is displayed as undefined rather than as a function.

Instant function mode

Functions are also objects, so they can serve as return values. The advantage of using a self-executing function is to declare an anonymous function immediately, to avoid defining a function that is not used once, and to exempt from the problem of naming conflicts, there is no namespace concept in JS, so it is very easy to have the function name conflict, once the naming conflict is final.

Mode one:

<script>
 (function () {
  var a = 1;
  return function () {
   alert (2);}
  ;
 } () ());//Eject 2, first parenthesis from execution, second parenthesis Execute internal anonymous function
</script>

Mode two: The direction of the self-executing function variable

<script type= "Text/javascript" >
  var result = (function () {return
   2;
  }) ()//The function

  alert (result) has been executed;//result points to the return value of 2 from the self-executing function, and error occurred if the eject cause ()
</script>

Mode three: Nested functions

<script type= "Text/javascript" >
  var result = (function () {return
   function () {return
    2;}
   ;
  } )();

 Alert (Result ()),//alert (Result) popup function () {return 2}
</script>

Mode four: The self-execution function assigns its return value to the variable

var abc = (function () {
   var a = 1;
   return function () {return
    ++a;
   }
  }) ()//The function that returns the return is returned to variable
 alert (ABC ());//If alert (ABC) pops up the code following the return statement;

Mode five: Function inside execute itself, recursion

This is a self executing function that executes itself internally, recursive function
ABC () {ABC ();}

Callback mode

callback function: When you pass a function write () as a parameter to another function called (), then at some point call () may execute (or invoke) write (). In this case, write () is called the callback function (callback functions).

Asynchronous Event Listener

The callback pattern has many uses, for example, when attaching an event listener to an element on the page, it actually provides a pointer to a callback function that will be invoked when the event occurs. Such as:

Document.addeventlistener ("click", Console.log,false);
The code example above shows the Console.log () of a document that is passed in bubbling mode to the callback function ().

JavaScript is especially useful for event-driven programming, because the callback mode supports programs to run asynchronously.

Timeout

Another example of using the callback pattern is when using a browser's window object to provide a time-out method: SetTimeout () and setinterval (), such as:

<script type= "Text/javascript" >
 var call = function () {
  Console.log ("100ms would be asked ...");
 settimeout (call, MB);
</script>

Callback mode in the library

When designing a JS library, the callback function comes in handy, and a library's code should use reusable code whenever possible, and callbacks can help achieve this generalization. When we design a large JS library, in fact, users do not need most of these functions, and we can focus on the core functions and provide "hook form" callback functions, which will make it easier to build, expand, and custom library methods

of curry

Curry technology is a technique that transforms a function into a new simplified (less acceptable parameter) function by populating multiple parameters into the function body. ——— "Proficient in JavaScript"

In simple terms, curry is a process of transformation in which we perform function transformations. The following example:

<script type= "Text/javascript" >
 //curry Add () functions function
 Add (x,y) {
  var oldx = x, Oldy = y;
  if (typeof Oldy = = "undefined") {return
   function (newy) {return
    oldx + newy;}
   ;
  }
  Fully apply return
  x+y;
 }
 Test
 typeof Add (5);//output "function"
 Add (3) (4);//7
 //Create and store a new function
 var add2000 = Add (watts);
 add2000 (10);//Output
</script>

When you call Add () for the first time, it creates a closure for the internal function that is returned. The closure stores the original x and Y values in the private variables oldx and Oldy.

Now, we will be able to use any function curry common methods, such as:

<script type= "Text/javascript" >
 //Ordinary functions Function
 Add (x,y) {return
  x + y;
 }
 Curry a function to get a new function
 var newadd = Test (add,5);
 Newadd (4);//9

 //Another option, direct call to new function
 test (add,6) (7);//Output
</script>

When to use curry

When it is discovered that the same function is being invoked, and that most of the arguments passed are the same, then the function may be a good candidate for curry

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.