Explain JavaScript's closures, iife, apply, Functions, and object _javascript techniques

Source: Internet
Author: User
Tags anonymous arrays closure function definition

Directory

First, Closure (Closure)

1.1, closures related issues

1.2, understanding the closures

Second, the object

2.1. Object Constants (literal)

2.2, take the value

2.3. Enumeration (traversal)

2.4, Update and add

2.5, the object of the prototype

2.6, delete

2.7, Packaging

Third, function

3.1. Parameter object (arguments)

3.2. Constructor function

3.3. Function call

3.3.1, call

3.3.2, apply

3.3.3, caller

3.3.4, callee

3.5. Execute function expression immediately (iife)

3.5.1, anonymous functions, and anonymous objects

3.5.2, functions and function expressions

3.5.3, immediately executing function expressions and anonymous objects

The writing of 3.5.4 and various Iife

3.5.5, Parameters

3.5.6, adding semicolons

The role of 3.5.7 and Iife

Deformation of 3.5.8 and Iife

Four, sample download

First, Closure (Closure)

1.1, closures related issues

Please put 10 div in the page, each div put the letter a-j, when clicked each div display index number, such as 1th div display 0, 10th Show 9; Method: Find all div,for cyclic binding events.

Sample code:

<! DOCTYPE html>
 
 

Run Result:

Because the function of clicking the event inside uses the external variable i have been changing, when we specify the click event and do not save a copy of I, this is also to improve performance, but not for our purposes, we want to let him execute the context of the copy of I, this mechanism is closure.

Modified code:

<! DOCTYPE html>
 
 

Run Result:

n is the value of the external function, but the internal function (click event) needs to be used, the return function before the n is temporarily resident in memory for the Click event to use, simply is the function of the execution context is saved, I generated multiple copies.

1.2, understanding the closures

Closure concept: When an intrinsic function is called, a closure is formed, a closure is a function that can read the internal variables of other functions, defined within a function, creates a closure environment, and allows the returned subroutine to grasp I so that the reference to this I can be maintained for subsequent executions. An intrinsic function has a longer lifecycle than an external function; A function can access the context in which it was created.

JavaScript language-specific "chain scope" structure (chain scope), where child objects look up the variables of all the parent objects at a level

Second, the object

An object is a collection of key/value pairs and has a connection to a prototype (prototype) to a hidden connection.

2.1. Object Constants (literal)

An object literal is the 0 or more key/value pairs contained within a pair of curly braces. Object literals can appear wherever an expression is allowed.

The definition of the object:

Null object
 var obj1={};
 Property in the object
 var obj2={name: "foo", age:19};
 var obj3={"nick name": "Dog"};
 Method
 var obj4={price:99 in the object
 ,
 inc:function () {
 this.price+=1;
 }
 }

What can be contained in an object:

Object constants can occur wherever an expression is allowed, and objects, arrays, and functions can be nested between each other in a variety of ways. Object values can be: arrays, functions, objects, basic data types, and so on.

Content that can be contained in an object
 var obj5 = [{
 name: ' Jack '
 }, {
 name: "Lucy",//constant
 hobby:["reading", "surfing", "code"],//array
 Friend:{name: "Mark", height:198,friend:{}},//Object
 show:function () {//function
 console.log ("Hello everyone, I am" +this.name);
 }
 }];
 This is dynamic in the object, pointing to the caller
 obj5[1].show ();

Output: Hello everyone, this is Lucy.

2.2, take the value

Method One: Direct use of dot number operation

 3 Take value
 var obj6={"nick name": "Pig", Realname: "Rose"};
 Console.log (obj6.realname);
 Console.log (obj6.nick name); Error

Method Two: Using indexers, when the key in the object has a space is

 3 Take value
 var obj6={"nick name": "Pig", Realname: "Rose"};
 Console.log (obj6["realname"]);
 Console.log (obj6["nick name"]);

2.3. Enumeration (traversal)

Method One:

var obj7={weight: "55Kg", "Nick name": "Pig", Realname: "Rose"};
 for (var key in OBJ7) {
 Console.log (key+ ": +obj7[key]);
 }

Run Result:

The output order is not guaranteed.

2.4, Update and add

If an attribute exists in the object, modify the corresponding value, if it does not exist, add it. Objects are passed by reference, and they are never copied

var obj8={realname: "King"};
 Obj8.realname= "Queen"; Modify
 obj8.weight=1000;//Add Properties
 obj8.show=function ()//Add method
 {
 console.log (this.realname+ "," + this.weight);
 }
 Obj8.show ();

Output:

queen,1000

var obj8={realname: "King"};
 Obj8.realname= "Queen"; Modify
 obj8.weight=1000;//Add Properties
 obj8.show=function ()//Add method
 {
 console.log (this.realname+ "," + this.weight);
 }
 Obj8.show ();
 
 Reference
 to Var obj9=obj8;//obj9 point to Obj8 reference
 obj9.realname= "Jack";
 Obj8.show ();

Output:

2.5, the object of the prototype

JavaScript is a dynamic language that is not the same as a static language such as C # and Java; JavaScript is not strictly typed, and it's easy to think of JavaScript as being composed of objects. Connections between objects to the prototype (prototype) implements extensions and inheritance of functionality. Each object is linked to a prototype object and can inherit properties from it, and all objects created by constants (literally) are connected to Object.prototype, which is the top-level (standard) object in JavaScript, similar to the root class in a high-level language.

Now we modify object objects in the system, add a creation method, specify the prototype to create the object, and implement a similar inheritance function:

<script type= "Text/javascript" >
 if (typeof object.beget!== "function")
 {
 object.create = function ( O) {
  //constructor, used to create object
  var F = function () {};
  Specifies the prototype of the object created by the constructor
  f.prototype = O;
  Call the constructor method to create a new object return a
  ();
 var rose={
 name: "Rose",
 show:function () {
  console.log ("Name:" +this.name);
 }
 ;
 Rose.show (); Output
 var lucy=object.create (Rose);//Simple thought: Create an object and inherit rose
 lucy.name= "Lucy";//Rewrite
 lucy.show ();
 </script>

Run Result:

A prototype relationship is a dynamic relationship, and if you modify the prototype, the object created by the prototype is affected.

var lucy=object.create (Rose); The simple view is: Create an object and inherit rose
 lucy.name= "Lucy";//Rewrite
 
 var jack=object.create (Rose);
 Jack.name= "Jack";
 
 Modify the method in the prototype
 rose.show=function () {
 console.log ("name->" +this.name);
 }
 
 Lucy.show ();
 Jack.show ();

Results:

About the prototype in the function will be mentioned again.

2.6, delete

 Delete attribute Delete
 mark.name; 
 Call method, Output: Name: undefined
 mark.show (); 
 Delete the function delete
 mark.show; 
 Error, Mark.show is not a function
 mark.show ();

Removing unused attributes is a good habit, and in some cases a memory leak can occur.

2.7, Packaging

The advantage of using object encapsulation is that you can reduce pollution opportunities for global variables by attaching attributes, functions, to one object.

Before encapsulation:

var name= "Foo"; Name is global, exposed
 i=1//Global, variables without the var keyword declaration are global, and the position relationship is not very function show
 () {//show is global, exposed
 console.log (" Name-> "+name);
 Console.log (++i);
 }
 I is the Global 2 show
 (); 
 3 show
 ();

After encapsulation:

Exposes only bar, using the closure package
 var bar=function () {
 var i=1;
 return{
  Name: "Bar",
  show:function () {
  console.log ("name->" +this.name);
  Console.log (++i); 
 }}; var bar1=bar ();
 2
 bar1.show ();
 3
 bar1.show (); 
 var bar2=bar ();
 2, because is encapsulated, and the closure, I is the local private
 bar2.show ();

Run Result:

Third, function

A function in JavaScript is an object, which is a collection of key/value pairs and has a connection to the prototype to the hidden connection.

3.1. Parameter object (arguments)

The first function has a default object called arguments, similar to an array, but not an array, which is the argument passed to the function.

<script type= "Text/javascript" >
 function Counter () {
 var sum=0;
 for (Var i=0;i<arguments.length;i++) {
  sum+=arguments[i];
 }
 return sum;
 }
 Console.log (Counter (199,991,1,2,3,4,5));
 Console.log (counter ());
 </script>

Run Result:

1205

0

The arguments here is an implicit object, not being declared in a function, where an intrinsic function can access any content of an external function, but cannot directly access the arguments and this object of the external function.

Function F1 ()
 {
 console.log (arguments.length);
 F2=function ()
 {
  console.log (arguments.length);
 }
 return f2;
 }
 var f=f1 (1,2,3);
 f ();

Run Result:

3

0

3.2. Constructor function

In JavaScript, an object constructor can create an object.

<script type= "Text/javascript" >
 ///////can be simply considered to be a type defined
 function Student (name,age) {
  This.name=name;
  This.age=age;
  This.show=function () {
  console.log (this.name+ ", +this.age);
  }
 }
 Call the constructor with the new keyword to create an object Tom
 var rose=new Student ("Rose");
 var jack=new Student ("Jack");
 
 Rose.show ();
 Jack.show ();
 </script>

3.3. Function call

3.3.1, call

Invokes one method of an object, replacing the current object with another object

call([thisObj[,args])

Hisobj can be selected. The object that will be used as the current object. Args will be passed a sequence of method parameters.

The call method can be used to invoke a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by Thisobj.

Example:

/* constructor
 /function Student (name,age) {
  this.name=name;
  this.age=age;
 }
 Show=function (add) {
  Console.log (add+ ": +this.name+", "+this.age");
 }
 Call the constructor with the new keyword to create an object Tom
 var rose=new Student ("Rose");
 var jack=new Student ("Jack");
 Call the Show method, specify the context, specify the calling object, this points to Rose, "Everyone is a parameter"
 Show.call (Rose, "everyone good");
 Show.call (Jack, "Hello");

Run Result:

The parameters in the call method can be omitted, the 1th argument represents which object is invoked on the method, or who, if unspecified, points to the Window object.

Example:

 var name= "Nameless";
 var age=18;
 Show.call ();

Results:

Undefined: nameless, 18

3.3.2, apply

apply([thisObj[,argArray]])

Applies a method of an object, replacing the current object with another object, similar to call.

If Argarray is not a valid array or is not a arguments object, it will result in a typeerror.

If you do not supply any of the Argarray and thisobj parameters, the Global object will be used as a thisobj and cannot be passed any parameters.

Is the same for the first parameter, but for the second argument:

Apply passes in an array of arguments, which is the combination of multiple arguments into an array, while call is passed as a call parameter (starting with the second argument).

such as Func.call (FUNC1,VAR1,VAR2,VAR3) corresponding apply is written as: Func.apply (FUNC1,[VAR1,VAR2,VAR3))

The advantage of using apply at the same time is that you can simply pass the arguments object of the current function as the second argument to apply

Sample code:

/* constructor
 /function Student (name,age) {
  this.name=name;
  this.age=age;
 }
 Show=function (greeting,height) {
  Console.log (greeting+ ": +this.name+", "+this.age+", "+height");
 }
 Call the constructor with the new keyword to create an object Tom
 var rose=new Student ("Rose");
 var jack=new Student ("Jack");
 Call the Show method, specify the context, specify the calling object, this points to Rose, "Everyone is a parameter"
 show.apply (rose,["Everyone Good", "178cm"]);
 Show.apply (jack,["Hello", "188cm"]);

Run Result:

As you can see from the example above, the 2nd parameter of apply is an array, and the contents of the array are mapped to the parameters of the invoked method, and if it is not as convenient to call as it is, it is easier to apply the parameters of the method directly arguments. You can replace call by simply changing it.

 function display () {
 show.apply (jack,arguments);
 }
 Display ("Hi", "224cm");

Results:

hi:jack,20,224cm

The call and apply operators in JavaScript can change the this point at random

The this pointer to a function points to window if it is not in the JavaScript language through new (including object literal definition), call, and apply to change the this pointer of the function.

As for the this pointer, my summary is: Who called the function, then the this pointer in this function is it; if it is not clear who called, then the window is called, then this pointer is window.

3.3.3, caller

When a function calls another function, the called function automatically generates a caller property that points to the function object that called it. If the function is not currently invoked, or is not called by another function, caller is null.

In earlier versions of JavaScript, the caller property of a function object was a reference to the function that called the current function

function Add ()
 {
 Console.log ("add called");
 The call function of the Add method, or null
 console.log (add.caller) If the call to the Add method is not a function;
 Function calc () {
 add ();
 }
 Call Add Method
 Add () directly; 
 Call Calc () indirectly through the Calc method
 ;

Run Result:

Caller and this are different, this is the object that invokes the method, and caller refers to the function that calls the function.

<script type= "Text/javascript" >
 function Add (n)
 {
 Console.log ("add called");
 if (n<=2) {return
 1;
 }
 Return Add.caller (n-1) +add.caller (n-2);
 }
 Function calc (n) {
 console.log ("calc called");
 return add (n);
 }
 1 1 2
 console.log (Calc (3));
 </script>

Results:

3.3.4, callee

When a function is invoked, its Arguments.callee object points to itself, which is a reference to itself.

function Add (n1,n2) {
  console.log (n1+n2);
  Arguments.callee (N1,N2); Point to Add method return
  Arguments.callee;
 }
 Add (1,2) (3,4) (5,6) (7,8) (8,9);

Run Result:

When you call the Add method for the 1th time, enter 3, and immediately return the function to call again, and then return to yourself after each call, which enables chained programming.

3.5. Execute function expression immediately (iife)

Iife, immediately-invoked function Expression, immediately executes the expression of functions

3.5.1, anonymous functions, and anonymous objects

Anonymous functions are functions that do not have names, and often use anonymous functions in JavaScript to implement event bindings, callbacks, and implementing private scopes at the function level, as follows:

 function () {
 Console.log ("This is an anonymous function");
 

Anonymous objects:

 {
 name: ' foo ',
 show:function () {
 console.log (this.name);
 }
 }

Anonymous functions that have no names are also called function expressions, and there is a difference between them.

3.5.2, functions and function expressions

The following is the difference between a function and a function expression when defined

A), functional definition (function declaration)

function Identifier ( Parameters ){ FunctionBody }

function function name (parameter) {functional Principal}

In the function definition, the parameter (Parameters) identifier (Identifier) is essential. If omitted, you will be prompted for an error:

Code:

 function () {
 Console.log ("This is an anonymous function");
 

Results:

b), functional expression (function Expression)

function Identifier(Parameters){ FunctionBody }

In a function expression, both parameters and identifiers are optional, and the difference from the function definition is that identifiers can be omitted.

In fact, "function Identifier (Parameters) {functionbody}" is not a complete function expression, complete function expression, requires an assignment operation.

Like what:var name=function Identifier(Parameters){ FunctionBody }

3.5.3, immediately executing function expressions and anonymous objects

 1 Normal definition function
 F1 () {
 console.log ("Normal definition F1 function");
 2 Misunderstood functions expression function
 () {
 Console.log ("Error unexpected token (");
 } ();
 3 Iife, the contents of parentheses are interpreted as functional expressions
 (function () {
 console.log ("Iife, Normal Execution");
 } ();
 4 function Expression
 var f2=function () {
 Console.log ("This is also considered a function expression");
 

Why is the 3rd type of writing so that it can be executed immediately and without an error? Because in JavaScript, parentheses cannot contain statements inside, when the parser interprets the code, it first encounters (), and then encounters the Function keyword automatically recognizes () the code inside as a function expression rather than a function declaration.

If you need to execute a function expression or an anonymous object immediately, you can use the following methods:

<! DOCTYPE html>
 
 

Run Result:

The writing of 3.5.4 and various Iife

The two most commonly used methods
(function () {/* Code/} ());//teacher Recommended writing
(function () {/* code/});//Of course, this also can
//bracket and JS some operators (such as = && | | , etc.) can be used to eliminate ambiguity//in function expressions and function declarations The
parser already knows that one is an expression and then the other defaults to the expression
//But the exchange of the two will error the
var i = function () {return 10;} ();
True && function () {/* code */} ();
0, function () {/* code */} ();
If you are not afraid of obscure code, you can also select the unary operator
!function () {/* Code/} ();
~function () {/* * Code/} ();
-function () {/* * Code/} ();
+function () {/* * Code/} ();
You can do the same. The
new function () {/* code
/} new function () {/* * Code/} ()///Join

If it is a function expression, it can be immediately followed by a "()" immediate execution.

If it is a function declaration, you can convert it to a function expression by using operators such as "()", "+", "-", "Void", "new", and then Add "()" to execute immediately.

3.5.5, Parameters

A function expression is also an expression of a function, and can also use parameters like a function, as follows:

 (function (n) {
 console.log (n);
 }) (100);

Output: 100

In fact, through the Iife can also form a similar block-level scope, when the program in the block in the use of external objects will be preferred to find the object within the block, and then look for objects outside the block, in turn up.

 (function (WIN,UNDFD) {
 win.console.log ("Hello" ==UNDFD);
 }) (window,undefined);

3.5.6, adding semicolons

To avoid an error with other JavaScript code, a semicolon is often added before Iife, indicating that all the preceding statements are ended and a new statement is started.

 var k=100
 (function (n) {
 console.log (n);
 }) (k);

The above script will complain because the JavaScript interpreter thinks 100 is the function name.

 var k=100
 ;(function (n) {
 console.log (n);
 }) (k);

That's right, the end of a line in JavaScript can be done with a semicolon, or without a semicolon, because a generic custom plug-in uses Iife, a separate piece of code that does not guarantee that a semicolon is added to the application, so it is recommended that you precede the iife with a semicolon.

The role of 3.5.7 and Iife

1), Improve performance

Reduce scope lookup time. A small performance advantage of using Iife is to pass the parameters of the anonymous function to the common Global Object window, document, and jQuery, referencing these global objects within the scope. The JavaScript interpreter first looks up the property in the scope and then looks up the chain up until the global scope. The global object is placed in the Iife scope to promote the lookup speed and performance of the JS interpreter.

function (window, document, $) {
(window, document, Window.jquery);

2), compressed space

Global objects are passed by parameters that can be anonymous to a more streamlined variable name when compressed

Function (W, D, $) { 
} (window, document, Window.jquery);

3), avoid conflict

Within an anonymous function, a block-level private scope can be formed.

4), dependent loading

can be flexible to load third-party plug-ins, of course, using modular loading better (amd,cmd), as shown below.

A.html and b.html files refer to common Common.js files at the same time, but only a.html need to use the Stuobj object, b.html do not need, but use other methods.

Student.js

var stuobj = {
 getstu:function (name) {return
 new Student (name);
 }
}
/* constructor
/function Student (name) {
 this.name = name;
 This.show = function () {
 console.log ("Hello," + this.name);
 }

Common.js

function Other1 () {}
function Other2 () {}
(function ($) {
 if ($) {
 $.getstu ("Tom"). Show ();
}) (typeof stuobj== "undefined"? false:stuobj);

A.html

<! DOCTYPE html>
 
 

B.html

<! DOCTYPE html>
 
 

Deformation of 3.5.8 and Iife

Maybe someone will say Iife put the parameters at the end, you need to move to the end of the document to see the parameters, more trouble, then the Iife can be transformed into the following form:

(function (n) {
 console.log (n);
 
 
 
 
 
 
 
 Think there are 30000 code
 
 
 
 
 
 
 
 } (100));

If there is a long code in the middle, parameter 100 can only be seen at the end of the document, the result of the deformation:

(function (exp) {
 exp ();
 } (function (n) {
 console.log (n);
 Think there's 30000 Code
 }));

There are two function expressions in the modified code, one as a parameter, that is, the function we want to accomplish is to output the number to the console, the other is to iife the function immediately executed, the main function function becomes the Iife parameter.

(Function (Win, Doc, $) {
 } (window, document, jQuery);
 (
 function (library) {
  Library (window, document, Window.jquery);
 }
 (Function (window, document, $) {
 })
 ;

Bootstrap's writing:

+function (yourcode) {
 yourcode (window.jquery, window, document);
 } (Function ($, window, document) {
  $ (function () {});//jquerydom load completion event
 });

In combination with call or apply:

 (function (x) {Console.log (x)}). Call (window,888);
 (function (x) {Console.log (x)}). Apply (window,[999]);

Output: 888 999

Four, sample download

Http://wd.jb51.net:81//201612/yuanma/javascript003-master_jb51.rar

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring some help, but also hope that a lot of support cloud Habitat community!

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.