JavaScript function and scope Summary introduction _javascript skills

Source: Internet
Author: User
Tags anonymous closure eval first string setinterval variable scope


Use functions in JS to note three points:

1, when the function is invoked, it is run in the grammatical environment when he is declared;



2, the function can not run itself, it is always called by the object, the function runs, the function body of the this pointer to the object that calls the function, if the function is called without explicitly specifying the object, this default point to window (except strict mode, this article does not involve strict mode);



3. A function is an object type data with executable code.



first, the declaration function



1. Using function keywords

code as follows:


function Myfun (a,b) {//Declaration of functions named Myfun


return a+b;

}




2. Declaring anonymous functions





function (a,b) {return a+b;} The anonymous function itself is not saved, because in JS the function is an object-type data, so the anonymous function can be assigned to the variable to save.



var myfun = function (a,b) {return a+b;}

3. Use function constructor functions//note Capitalize first letter



Functions are a function of JS built-in, which is the constructor of all function objects. (Other data objects also have their own built-in constructors, such as Number,object, which have their own constructors that function, because they are all functions).



var myfun = new Function (' a,b ', ' return a+b; '); One of the last arguments is the function body, the preceding arguments are the formal parameter names of the functions, which are indeterminate because they need to be constructed with string literals, which are often very inconvenient to use when the function is longer, and may be used to construct a specific return value to replace the Eval function.



It should be noted that both global and global functions can be considered properties of Window objects, and if there are functions and variables with the same name, there can be only one entry in effect (actually only one attribute), try the following code.


 code as follows:

function A () {alert (' a ');}


alert (WINDOW.A); Accessing the properties of a Window object can also save Windows from not writing

var a=1;

alert (WINDOW.A);




The declarations of functions and variables occur in the code parsing period. The difference is that a variable is declared unassigned only in the parsing period, so when a function and variable with the same name exists in the same scope, the function with the same name is in effect before the code runs to the variable assignment ( The value of the Window object property is overwritten with the new data, and the variable takes effect (but note that in Firefox, the function declared within the with pseudo closure can only be invoked after the declaration, that is, there is no advance declaration of the function in Firefox's with).


 code as follows:

With ({}) {
A (); Under Firefox A is not declared
function A () {Console.log ("function A is called");}
}



If a function of the same name is declared more than once, subsequent declarations will overwrite the preceding declaration, such as:

 code as follows:

alert (func1);//Eject func1 () {alert (2);}


Func1 () {

Alert (1);

}

alert (FUNC1); Pop-up func1 () {alert (2);}

Func1 () {//This is the last declared func1, whichever is the function

Alert (2);

}

alert (FUNC1); Pop-up func1 () {alert (2);}

var func1 = function () {//note, this is a variable assignment, not a function declaration

Alert (3);

}

alert (FUNC1); Eject function () {alert (3);}




In addition to browsers under IE8 and IE8, function declarations in expressions return anonymous functions and do not successfully declare named functions


 code as follows:

if (function Fun () {}) {
alert (fun); Error, the function with name fun is not successfully declared, but a function is successfully declared in IE8 and the following browsers fun


}

(function Fun () {});

alert (fun); Error but even in IE8, a named function in an expression cannot overwrite a variable with the same name as the following:

var fun = 1; The variable cannot be overridden by a function name in a function expression
var f = function fun () {};
alert (f); function Fun () {};
alert (fun); 1




Note the difference:





if (fun = function () {}) {
alert (fun); OK, here we declare a variable that holds an anonymous function



}



The JS function is a reference type Object



var a = function () {};
var b=a;
b.x=2;
alert (a.x); 2



Second, the function of the parameters



The JS function will not check the number of parameters passed in the function call and the definition of the number of formal parameters is consistent, generally, JS function calls can receive the number of 25, of course, different browsers may have differences, ECMAScript standard for this point is not standardized.



You can use the arguments object of a function if you are unsure of how many arguments were passed in when the function was called.



Arguments a bit like an array, arguments.length for the number of arguments passed in, Arguments[0] is the first argument, Arguments[1 is the second argument, and so on ...



The length property of a Function object: This property is rarely used, and even very few people know that the length property of a function is the number of formal arguments when the function is defined.


 code as follows:

function Myfun (a,b) {


alert (arguments.length); Number of arguments actually passed in when the call was popped

Alert (arguments[0]); corresponding parameter A

return a+b;

}

alert (myfun.length); Number of formal parameters, 2




The arguments object also has other properties, such as the commonly used Arguments.callee, pointing to the function itself.





Note: If the function internally declares a child function with the same name as the formal parameter (the function with the same name is in effect when the variable is not assigned to the same domain), the corresponding value of arguments is also modified, but declaring a variable with the same name in the scope with VAR does not cause the arguments The parameter value is replaced by the function (but Firefox is still replaced).


 code as follows:

function AA (A, b,c) {A problem of//JS group
function A () {}

Console.log (a); Function A
Console.log (AA);

If Var A is not in scope, then arguments[0] is function A (Friefox (version 17) must be function a)
Console.log (Arguments[0]);
var a = "ee"; Logout of this sentence, Arguments[0] will become a function
var AA = "444";
arguments = 6;
Console.log (a);
Console.log (AA);
Console.log (arguments);
}
AA (1,2,3);



third, return value of function





The JS function returns a value using the return statement.



All data types can be the return value of a function (including functions), and the JS function can have no return value.



Fourth, function call



The function itself is not running, and when it runs, there is always an object that calls it.



By default, in any syntax environment, if you do not explicitly specify a call object for a function, or call the function through a Window object, the this pointer in the function body points to the Window object.


 code as follows:

function Myfun (a,b) {


alert (this);

return a+b;

}

Myfun (1,2); Call the function and pass in 2 parameters, the 2 parameters corresponding to the formal parameter a,b call the function, if the number of parameters passed over the form parameter, only with arguments subscript to receive.




Alert (this) pops up the Window object because no object is explicitly specified to invoke the function. This invocation method is the most common.





There are three call object methods for explicitly specifying a function:



1. If a function is assigned an attribute value of an object, this function can only be accessed through this object (but not by saying that the function can only be invoked by that object), and this function is called by this object in a way that resembles a method call in an Object-oriented programming language (actually used in JS as a way of calling it).


 code as follows:

var obj={}; Define an Object


Obj.fun=function (a,b) {

alert (this); Eject this pointer

return a+b;

}//object property value is a function

alert (obj.fun);//access fun function. This function can only be accessed through this object

Obj.fun (1,2); Using the Obj object to invoke the fun function, the Obj object pops up. This approach is also known as the fun method that invokes the Obj object.




2, any specified function of the call object: In a syntax environment, if you can access both the function fun and object obj, as long as you want to, you can specify through the Obj object to call the fun function. There are 2 ways to specify a method: The call method and the Apply method. (Because the Window object is the top-level object in the browser environment, the window object can be accessed in any syntax environment, so any function can be invoked through the Window object)


 code as follows:

function Fun (a,b) {


alert (this);

return a+b;

}

var obj={};

Fun.call (obj,1,2); The fun function is called through the Obj object, and 2 arguments are passed in, and the pop-up pointer is the Obj object.


var obj2={};

obj2.fun2 = function (a,b) {//obj2 object's property fun2 is a function

alert (this);

return a+b;

};

Obj2.fun2.call (obj,1,2); Using the Obj object to invoke the function saved by the value of the Fun2 property of the Obj2 object, the pop-up this pointer is an obj object

A more covert method call: An array calls a function [9,function () {alert (this[0]);}] [1] ();

Use the Window object to invoke a function the following methods are equivalent
Fun (1,2);
Window.fun (1,2); If the fun function is a global function
Fun.call (window,1,2);
Fun.call (this,1,2); If the code is in a global environment (or within a function that is called by a Window object), because this is the syntax environment that points to the Window object.
Func.call (); If the function does not require a reference
Func.call (null,1,2);
Func.call (undefined,1,2); var name = "Window";
function KKK () {
Console.log (this.name); Not IE
}
KKK (); Window
Kkk.call (KKK); The KKK function was called by itself




Another error that is more easily overlooked is that in a method of object A, a method call using the B object is executed, attempting to use this in the method of a B object to access A object, which is common in various callback functions, and the most common scenario is the use of this in Ajax callback functions.


 code as follows:



var obj = {


Data:null,


Getdata:function () {


$.post (Url,{param:token},function (databack) {//jquery Ajax post method


This.data = Databack; An attempt was made to assign the data returned by the server to Obj.data, but this here already points to the Ajax object of JQuery


}, ' json ');


}


}





Correct procedure
var obj = {
Data:null,
Getdata:function () {
var host = this; Save a reference to an Obj object
$.post (Url,{param: "token"},function (databack) {
Host.data = Databack;
}, ' json ');
}
}





3. Apply method call:





The only difference between the Apply method and the call method is that the function argument is different.



Obj2.fun2.call (obj,1,2); Change to apply Way is obj2.fun2.apply (obj,[1,2]);



Apply uses an array of classes to pass the parameters, except for the divisor group, which can also use arguments, htmlcollection, but arguments is not an array, such as:



var obj={};



function fun_1 (x,y) {



function Fun_2 (a,b) {



return a+b;



}



Fun_2.apply (obj,arguments); Using the Fun_1 arguments object to pass the argument, is actually receiving the X,y



}apply in IE8 and IE8 browser yo 2 questions



In call and apply calls, if you pass in scalar data (True/false, string,number), the function will wrap the basic data they passed in as an object, then point to the wrapped object, and try the following code.
function A () {



Alert (typeof this);



alert (this.constructor);



alert (this);



}



A.call (FALSE);



A.call (100);



A.call (' Hello ');



You can even use this feature to pass parameters, but this usage is not recommended:



function A () {alert (1+this);}//object automatic type conversion in operation



A.call (100); 101



4. function as Object Builder



When a function runs as an object constructor using the new operation, this points to the newly constructed object, and if the return value of the constructor is not an object other than null, the constructor runs out and returns the object to which it points, otherwise the original definition is returned.


 code as follows:

function Fun () {


THIS.A = 1;

this.b = 3;

Console.log (this); {A:1,b:2}

return {a:999}; Plus this, will return {a:999}

}

var obj = new Fun (); obj = {A:1,b:2}, if there is no argument, you can also write var obj = new Fun;




v. Function scopes





JS variable scope is functional level, in JS does not resemble the block-level scope of C language.



The top-level scope of the JS programming environment is a range under window objects called Global scopes, and variables in global scopes are called global variables.



The variables inside the JS function cannot be accessed outside of the function, but the variables outside the function can be accessed within the function, and the variables within the function are called local variables.



The JS function can be nested, and the layers of multiple functions are nested in multiple scopes, which is called JS's scope chain.



The variable access rule for the JS scope chain is: If there is a variable to be accessed within the current scope, the variable of the current scope is used, otherwise it is found in the previous scope until the global scope, if it is not found, is not declared.



Note that the declaration of a variable is completed in the code parsing period, if the Declaration and assignment statement for the current scope variable is written after the variable access statement, the JS function considers that the variable being accessed by the current scope is no longer being looked up to the parent scope, however, because the variable's assignment occurs during the code run, Access to the variable will be undefined.



Such as:


 code as follows:

var c=1000;


function out () {

var a=1;

var b=2;

function Fun () {

alert (a); Undefined

var a=10;

alert (a); 10

alert (b); 2

alert (c); 1000

}

Fun ();

}

Out ();




Vi. calls to anonymous functions





The use of anonymous functions in JS is very important, because all the data in JS are objects, including functions, so often use functions as a parameter or return value of another function.



If the anonymous function is not saved, it is freed from memory when it is run.



Anonymous functions are typically called by simply placing anonymous functions in parentheses instead of function names. Such as:



(function (a,b) {return a+b;}) (1,2); Declares and executes an anonymous function, passing in two parameters: 1 and 2



Or



(function (a,b) {return a+b;} (1,2));



The following wording is wrong:



function (a,b) {return a+b;} (1,2);



Because the semicolon in the statement end of JS can be omitted, the JS engine thinks function (a,b) {return a+b} Is the end of a statement, so the anonymous function only declares that it is not called, and if the statement has no parameters (1,2) written (), it can also cause an error, and the JS Hollow bracket is a syntax error.



The following is the correct wording.



var ab = function (a,b) {return a+b;}  (1,2); Ab=3



JS parsing syntax, if the expression appears in the assignment operation or operator operations, is "greedy match" (try to evaluate)



Function (t) {return 1+t;} (); Error
var f = function (t) {return t+1;} (); Ok



~ function (t) {return t+1;}  (); Ok
+ function (t) {return t+1;} (); Ok



If you just want to assign an anonymous function to a variable, remember to append the semicolon to the assignment statement, otherwise, if the parentheses are followed by a function call, especially when the parentheses are separated from the end of the function, this error is often difficult to find.



In actual development, an anonymous function may be returned in the form of an operation value, which may not be easily seen, such as



var a = 1;
var obj = {a:2,f:function () {return this.a;}};



(1,OBJ.F) (); 1 comma expression back up an anonymous function, and when this anonymous function is invoked, the thsi in the function Body points to window



Declaring and running an anonymous function immediately is called a "self-execution function," which is often used to encapsulate a piece of JS code. Because of the feature of function scope, the variables inside the function cannot be accessed externally, the code placed in the functions will not affect the outside code, and can avoid the variable pollution. JS Development is very easy to cause variable pollution, in the development of other coders often introduced code, if the different coders defined by the different meaning of the global variable or function, it caused the variable pollution, the same scope of the same name variable or function, later will cover the front.



(function () {



Own code ...



) (); Anonymous functions can also cause memory to be released in time: Because variables are declared within anonymous functions, if the variables are not referenced outside of anonymous functions, the function is completed and the memory occupied by the variables inside is immediately released.



Name of the function: in Firefox and other browsers, the function has a Name property, is the function name, but this property does not exist in IE, in addition, the name of the anonymous function is a null value.



var a=function () {}
alert (a.name); Undefined,a is a variable that stores an anonymous function
Function B () {}
alert (b.name); b, but undefined for IE



When a function is invoked, it runs in the environment in which he is defined



No matter where the function is invoked, and by whom it is invoked, it is not possible to change the syntax environment when it is declared, which determines the operating environment of the function


 code as follows:



var x=99;





var inerfun=null;



function Fun1 () {



alert (x);



}



function holder () {



var x = 100;



var fun2 = fun1;



Inerfun = function () {alert (x);}



Fun1 (); 99



Fun2 ();//99



Inerfun (); 100



}



Holder ();



Fun1 (); 99



Inerfun (); 100






Another example:



var x = 100;
var y=77;
var a1={
X:99,
Xx:function () {
var y=88; If you annotate this variable, Y will be 77 of the global variable.
alert (y); Without using the this pointer, an object calling a function cannot affect the value of Y, and the function runs from here to the value of the scope chain.
alert (this.x); Using the this pointer, call the function's
}
}



A1.XX ();
A1.xx.call (window);



var JJ = a1.xx;



JJ (); Effect with a1.xx.call (window); Try the following code



var x=99;
Function xb () {
this.x=100;
THIS.A = (function () {return this.x}). Call (this); When new is executed, the anonymous function is instantiated by the object called
this.b = (function () {return this.x}) (); When new is executed, the anonymous function is called by the window
This.method = function () {return this.x;}
}




var xbobj = new XB ();
Console.log (xbobj.x);
Console.log (XBOBJ.A);
Console.log (XBOBJ.B);
Console.log (Xbobj.method ());





Note the concepts of distinguishing between the object that calls the function, the syntax environment when the function is declared, and the syntax environment of the function call statement





1. The object that calls the function (or how the function is called) determines who the this pointer in the function's body is pointing to when the function is run



2, the function declaration when the syntax environment determines the function runtime access rights



3. The syntactic environment of the function call statement determines whether the function can really be invoked and when it is invoked (only the function can be called if it is visible in a syntactic environment).



When a function is running, it produces a arguments object that can access parameters within the incoming function, and arguments has a property that points to the function itself: Arguments.callee.



When a function runs, the caller property of the function can point to the function where the function call statement is located, for example, the A function is called in the B function, then when the A function is run, the A.caller points to the B function, if the A function is invoked in the global environment A.caller=null



The values of arguments and A.caller are directly associated with each invocation of the function, and they are all generated when the function is run and can only be accessed within the function body.



IE8 and IE8 in the following browsers, the Arguments.caller in the A function (IE9 after this property is removed) points to a.caller (arguments = = Arguments.caller.callee) at execution time.



function calls in real-time parsing of strings: eval (), New Function (), settimeout (), SetInterval ()



Eval () and Window.eval ()


 code as follows:

function A () {
Console.log (' Out of B ');
}
Function B () {
function A () {Console.log ("in B");}
var f = function () {a ();};
Eval (' A () '); In B
Window.eval (' A () '); Out of B, ie 6\7\8 in B, ie 9 out of b
(New Function (' A (); ') (); Out of B
SetTimeout (' A () ', 1000); Out of B
SetTimeout (f,2000);//in B
}
b ();



The code in eval () executes in the scope of the Eval () statement:


code as follows:



var objinit = function () {


var param = 123;


return {


Execute:function (codes) {


eval (codes);


},


Setcallback:function (f) {


This.callback = f;


},


Firecallback:function () {


This.callback && This.callback.call (this);


},


Getparam:function () {


return param;


}


}


};





var obj = Objinit ();
var param = ' Outerparam ';
Console.log (Param,obj.getparam ()); Outerparam 123
Obj.execute (' param = 456 ');
Console.log (Param,obj.getparam ()); Outerparam 456
Obj.setcallback (function () {eval ("param = 8888")});
Obj.firecallback ();
Console.log (Param,obj.getparam ()); 8888 456
Obj.setcallback (function () {eval ("eval (param = 9999)")});
Obj.firecallback ();
Console.log (Param,obj.getparam ()); 9999 456eval ()





The parsed code in the string is in the scope of the eval, and Window.eval () is run in the top-level scope (lower version of Chrome and the same as eval () below IE9).





In IE, Window.execscript (); Equivalent to Window.eval ()



The code parsed by the first string parameter of the new function (), settimeout (), setinterval () is executed at the top-level scope.



Viii. function closure



To understand the function closure, first understand the JS garbage automatic recycling mechanism.



Number, String, Boolean, undefined, null replicate values in operations and assignment operations, and data of object types are passed by reference.



JS's same object data can be referenced multiple times, if an object is no longer referenced, or if the two objects are not referenced by a third party, the browser automatically frees up the memory space it occupies.



Functions are referenced: The function is assigned to the property value of other objects, or the data defined within the function is used outside of the function, and the closure is formed based on the latter case.


 code as follows:

var F;


function Fun () {

var a = 1;

f = function () {return ++a;};

}

Fun (); Create a closure

f (); a=2 in closure

f (); A = 3 in closure, simulating static variables




The anonymous function declared inside the fun is assigned to the variable f outside fun, variable A, declared within fun, is used within the anonymous function so that f can access variable A, in order to maintain this access (F execution requires access to a, but when execution is undetermined), fun () The resulting variable A cannot be released (unless the function in F is released), a closure is generated (variable A is closed for use by F).





The key to creating a closure is that a function B declared in function A is outside of a, and the B function uses the data generated in function a (declaration or by value).



There are several different ways to function B outside of function A, such as:


 code as follows:

function Fun () {
var a = 1;


return {a:123,b:456, c:function () {return ++a;}};

}

var f = fun ();

F.C (); a=2





Broadly speaking, when a function runs, it forms a closure, and when no data is referenced outside the function, the closure's lifecycle is short: The function is released after execution.



Closure independence: Even multiple closures generated by the same function are independent of each other


 code as follows:

function Fun () {


var a = 1;

return function () {return ++a;};

}

var f1 = fun (); A closed bag

var F2 = fun (); Another closure.

Alert (F1 ()); 2

Alert (F1 ()); 3

Alert (F2 ()); 2

Alert (F2 ()); 3




The variable A in these two closures is a different data, every time a closure is generated, fun () executes once, and the variable declaration statement executes once.





In JS OOP programming, closures can be used to simulate private members and construct monomer classes.


 code as follows:

function Makeitem (name,val) {
var myname,myval; Private property


Private method
function SetName (name) {
Myname=name;
}

Private method
Function Setval (val) {
Myval=val;
}

Invoke internal private method when executing new construction object
SetName (name);
Setval (Val);

Public methods
This.getname=function () {
return myname;
}

This.getval=function () {
return myval;
}
}

var obj = new Makeitem ("name", 100);
Obj.myname; Undefined cannot access private properties outside
Obj.getname (); Ok




The following is a method of building a monomer class


 code as follows:



var Singleton = (function () {





var instance = null; To save an instance of a monomer class in a closure



var args = null;



var f = function () {



if (!instance) {



if (This===window) {



args = Array.prototype.slice.call (arguments,0);



Instance = new Arguments.callee ();



}else{



This.init.apply (this,args| | arguments);



instance = this;



}



}



return instance;



};



F.prototype = {



Init:function (a,b,c) {



THIS.A = A;



this.b = b;



THIS.C = C;



This.method1 = function () {Console.log ("Method 1");



This.method1 = function () {Console.log ("Method 1");



Console.log ("init instance");



}



};



F.prototype.constructor = F.prototype.init;



return F;






})();




Use of monomer
var obj1 = Singleton (1,2,3);



var obj2 = new Singleton ();



var obj3 = new Singleton ();



Console.log (OBJ1===OBJ2,OBJ2===OBJ3); True



Console.log (OBJ1);



A single class declaration function



var singletondefine= function (fun) {



Return (function () {



var instance = null;



var args = null;



var f = function () {



if (!instance) {



if (This===window) {



args = Array.prototype.slice.call (arguments,0);



Instance = new Arguments.callee ();



}else{



Fun.apply (this,args| | arguments);



instance = this;



}



}



return instance;



};






F.prototype = Fun.prototype;



F.prototype.constructor = fun;



return F;



})();



};



var fun = function (a,b,c) {



THIS.A = A;



this.b = b;



THIS.C = C;



This.method1 = function () {Console.log ("Method 1");



Console.log ("init instance");



};



FUN.PROTOTYPE.METHOD2 = function () {Console.log (' Method 2 ');




Monomer class declaration function usage
var Singleton = Singletondefine (fun);



var obj1 = Singleton (8,9,10);



var obj2 = new Singleton ();



var obj3 = new Singleton (3,2,1);



Console.log (OBJ1===OBJ2,OBJ2===OBJ3);



Console.log (OBJ1);



Console.log (Obj1.tosource ()); Firefox



Obj1.method1 ();



OBJ1.METHOD2 ();





IE6 memory leaks and closures





In IE 6, a circular reference to a Non-native JS object (DOM, etc.) can lead to memory leaks, which should be noted when using closures when referring to non-JS native object references.



function Fun () {



var node = document.getElementById (' a ');
Node.onclick = function () {alert (node.value);};



node = null; Interrupting circular references to prevent memory leaks



Node holds a DOM object that exists outside of fun (and always exists, even if the deletion is only removed from the document tree), fun after execution, and a circular reference (Node-function-node) of the DOM object and the callback function, in IE 6 A memory leak occurs under.


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.