A summary of JavaScript functions and scopes

Source: Internet
Author: User
Tags closure first string variable scope

Use the function in JS to note three points:
1, when the function is called, it is run in the syntax environment when he is declared;

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

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

I. Declaring functions

1. Using the Function keyword

The code is as follows:

function Myfun (A, B) {//DECLARE functions named Myfun

return a+b;

}


2. Declaring anonymous functions

function (A, b) {return a+b;} The anonymous function itself cannot be saved, because the function in JS 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

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

var myfun = new Function (' A, B ', ' return a+b; '); The last parameter is the function body, the preceding parameters are the formal parameter name of the function, the number is variable, because it is necessary to use the string parameter to construct, the function is long when this kind of writing is very inconvenient, generally rarely used, perhaps you will use it to construct a specific return value to replace the Eval function.

It is important to note that both global and global functions can be considered properties of the Window object, and if there are functions and variables with the same name, only one takes effect (actually, there is only one property), try the following code.

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

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

var a=1;

alert (WINDOW.A);


The declaration of functions and variables occurs during the code parsing period, except that variables are declared in the parsing period only, so when a function or variable with the same name exists within the same scope, the function with the same name takes effect before the code runs to the variable assignment, and the variable with the same name is assigned after the value ( Overwrite the value of the Window object's property with the new data), the variable takes effect (but note that in Firefox, functions declared within the with pseudo-closure can only be invoked after the declaration, that is, there is no pre-declaration of the function in Firefox's with).
The code is 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, the later declaration overrides the one previously declared, such as the following code:
alert (func1);//Popup func1 () {alert (2);}

Func1 () {

Alert (1);

}

alert (FUNC1); Popup func1 () {alert (2);}

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

Alert (2);

}

alert (FUNC1); Popup func1 () {alert (2);}

var func1 = function () {//note, here is the variable assignment, not the function declaration

Alert (3);

}

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


In addition to browsers IE8 and IE8, function declarations in expressions return anonymous functions and do not successfully declare named functions
The code is as follows:
if (function Fun () {}) {
alert (fun); Error, the function named fun is not declared successfully, but a function is declared successfully in the browser IE8 and below

}

(function Fun () {});

alert (fun); Error but even in IE8, the named function in the expression cannot overwrite the variable that is used for the following name:

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, this declares 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 parameters of the function

The JS function does not check the number of arguments passed in when a function call is consistent with the number of parameters when defining him, generally, the number of arguments that can be received when the JS function is called is 25, of course different browsers may have differences, and the ECMAScript Standard has no specification for this point.

You can use the arguments object of a function if you are not sure how many arguments are passed in when the function is called.

Arguments is a bit like an array, called a pseudo-array, it is used to hold the data of the argument, arguments.length 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 the Function object: This property is seldom used, and even few people know that the length property of the function is the number of formal arguments when the function is defined.

The code is as follows:
function Myfun (A, b) {

alert (arguments.length); The 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


Arguments objects also have other properties, such as common Arguments.callee, that point to the function itself.

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

The code is as follows:
function AA (A, b,c) {//js Group of questions
function A () {}

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

If there is no var a within the scope, then Arguments[0] is function A (Friefox (version 17) must be function a)
Console.log (Arguments[0]);
var a = "ee"; Write off this sentence, Arguments[0] will become a function
var AA = "444";
arguments = 6;
Console.log (a);
Console.log (AA);
Console.log (arguments);
}
AA (n/a);
third, the return value of the function

The JS function returns a value using the return statement.

All data types can function as return values (including functions), and the JS function can have no return value.

Four, function call

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

By default, in any syntax environment, if the calling object of a function is not explicitly specified, that is, by invoking the function through a Window object, the this pointer in the body of the function points to the Window object.

The code is as follows:
function Myfun (A, b) {

alert (this);

return a+b;

}

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


Because the object that called the function is not explicitly specified, alert (this) pops up the Window object. This method of invocation is the most common. There are three methods to display the calling object for a specified function:

1, if a function is assigned to a property value of an object, the function can only be accessed through the object (but not that the function can only be called by the object), this function is called by the object in a way similar to a method call in an object-oriented programming language ( In fact, JS is also used to the use of the method of this name).

The code is as follows:
var obj={}; Defining an Object

Obj.fun=function (A, b) {

alert (this); Eject this pointer

return a+b;

}//object property value is function

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

(Obj.fun); Using the Obj object to invoke the fun function, the Obj object pops up. This approach is also known as the fun method for invoking obj objects.


2, the calling object of any specified function: In a syntax environment, if you can access both the function fun and the object obj, you can specify to invoke the fun function through the Obj object as long as you want. 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 called through the Window object)
The code is 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 parameters are passed in, and the pointer pops up as an obj object.

var obj2={};

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

alert (this);

return a+b;

};

Obj2.fun2.call (obj,1,2); The function saved by the Fun2 property value of the Obj2 object is called through the Obj object, and the This pointer pops up as the Obj object

More covert method calls: Array calls a function [9,function () {alert (this[0]);}] [1] ();

There are several methods that are equivalent to invoking a function using the Window object
Fun (All);
(Window.fun); If the fun function is a global function
Fun.call (window,1,2);
Fun.call (this,1,2); If the code is in the global context (or inside a function called by the Window object), because this is the syntax environment, this is the point to the Window object.
Func.call (); If the function does not need to pass a parameter
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 prone to neglect is that in the method of the A object, a method call using the B object is performed, and an attempt is made to use this in the method of the B object to access the A object, which is common in various callback functions, and the most common scenario is the use of this in the Ajax callback function.
The code is 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 here the this already points to JQuery's Ajax object
}, ' json ');
}
}

Correct practice
var obj = {
Data:null,
Getdata:function () {
var host = this; Saving references to obj objects
$.post (Url,{param: "token"},function (databack) {
Host.data = Databack;
}, ' json ');
}
}


3, apply method invocation:

The only difference between the Apply method and the call method is that the function has different methods of parameter transfer.

Obj2.fun2.call (obj,1,2); To apply the way is obj2.fun2.apply (obj,[1,2]);

Apply uses the class array method to pass the parameter, in addition to the divisor group, you can also use arguments, htmlcollection to pass the parameter, 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, actually receives 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 that they pass in as an object, and then point this 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 operations

A.call (100); 101

4. Function As Object Constructor (constructor)

When the function is run 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 finishes running to return the object to which this is pointing, otherwise the original defined object is returned.

The code is as follows:
function Fun () {

THIS.A = 1;

this.b = 3;

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

return {a:999}; Add this to return {a:999}

}

var obj = new Fun (); obj = {A:1,b:2}, if there are no parameters, can also be written as var obj = new Fun;


v. Function scope

The variable scope of JS is function-level, and there is no block-level scope like C in JS.

The top-level scope of the JS programming environment is the scope under the Window object, called the global scope, and the variables in the global scope are called global variables.

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

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

The variable access rules for the JS scope chain are: if there are variables to access within the current scope, the variables of the current scope are used, otherwise the variables are found in the previous scope, until the global scope, if not found, the variable is not declared.

Note that the declaration of a variable is completed during the code parsing period, and if the Declaration and assignment statements of the current scope's variables are written after the variable access statement, the JS function will assume that the current scope already exists to access the variable that is no longer looked up to the ancestor scope, but because the assignment of the variable takes place during the code run time, The access to the variable will be undefined.

The code is 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. invocation of anonymous functions

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

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

The way anonymous functions are called is typically to place anonymous functions in parentheses instead of function names. Such as:

(function (A, b) {return a+b;}) (a); Declare and execute an anonymous function that passes two parameters at run time: 1 and 2

Or

(function (A, b) {return a+b;} ());

The following is an incorrect notation:

function (A, b) {return a+b;} (a);

Since the semicolon in the end of the statement in JS can be omitted, the JS engine will consider function (a, b) {return a+b;} Is the end of a sentence, so the anonymous function only declares that it has not been called, if the statement does not have a parameter () written (), also causes an error, JS Hollow parenthesis is a syntax error.

The following is the correct wording.

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

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

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 add a semicolon after the assignment statement, otherwise, it is often difficult to find the error when the parentheses are followed by a function call, especially when the parentheses are separated from the end of the function.

In real-world development, anonymous functions may be returned as operands, which may not be easy to see, such as

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

(1,OBJ.F) (); 1 Comma expression thsi an anonymous function, and when the anonymous function is called, the body of the function points to the window

Declaring and immediately running an anonymous function is called a "self-executing function", and self-executing functions are often used to encapsulate a section of JS code. Because of the function scope, the variables inside the self-executing function cannot be accessed externally, and the code inside the function does not affect the outside code, which can avoid the pollution of the variables. JS Development is very easy to cause variable pollution, in the development of the code developed by other coders often, if different coders define the same name with different meanings of global variables or functions, it will cause the variable pollution, the same scope of the occurrence of the same name variable or function, later will overwrite the previous.

(function () {

Own code .....

}) (); Anonymous functions also allow memory to be released in a timely manner: Because variables are declared within anonymous functions, if the variables are not referenced outside of the anonymous function, then the function is completed and the memory occupied by the variables is immediately released.

Function name: In a browser such as Firefox, the function has a Name property, which is the function name of the function, 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 the function is called, it runs in the environment where he is defined

No matter where the function is called and who is called, it cannot change the syntax environment when it is declared, which determines the environment in which the function is run.

The code is 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 comment on this variable, y will be 77 of the global variable.
alert (y); Without using the this pointer, the object calling the function cannot affect the value of Y, and the function will search for values from here by 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); Same//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 called by the instantiated object.
this.b = (function () {return this.x}) (); When new is executed, the anonymous function is called by 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 the object that invokes the function, the syntax context of the function declaration, and the syntax context of the function invocation statement

1. The object that invokes the function (or how the function is called) determines who the this pointer in the function body refers to when the function is run.

2. The syntax environment of the function declaration determines the access rights when the function is run.

3. The syntax environment of the function call statement determines whether the function can actually be called and when it is called (only if the function is visible in a syntax environment, this function can be called).

At run time, the function produces a arguments object that can access the arguments within the passed function, and arguments has a property that points to the function itself: Arguments.callee.

When the function is run, the caller property of the function can point to the function where the function is called, for example, the A function is called in the body of the B function, and when the A function runs, A.caller points to the B function, and if the A function is called in the Global environment A.caller=null

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

IE8 and IE8 The following browsers, the inside of a function arguments.caller (after IE9 this property is removed) points to a.caller when execution arguments (Arguments.caller.callee = = = A.caller).

viii. function calls in real-time parsing of strings: eval (), new function (), setTimeout (), setinterval ()

Eval () and Window.eval ()

The code is 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 within the scope where the eval () statement is located:
The code is 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 where eval is located, and Window.eval () is run at the top-level scope (low version chrome and below IE9 with Eval ()).

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

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

Nine, function closure

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

Number, String, Boolean, undefined, null are copied in the operation and assignment operations, and data of the object type is passed by reference.

JS of the same object type data may be referenced multiple times, if an object is no longer referenced, or two objects are not referenced by a third party, the browser will automatically free its occupied memory space.

A function is referenced: The function is assigned the property value of another object, or the data defined inside the function is used outside the function, and the closure is formed based on the latter case.

A closure is a function that has permission to access another function.

The code is as follows:
var F;

function Fun () {

var a = 1;

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

}

Fun (); Generate a closure

f (); a=2 in closures

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


The anonymous function declared in the fun is assigned to the variable f outside of the fun, the anonymous function uses the variable a declared in the fun, so f can access the variable A, in order to maintain this access (F execution needs to access a, but when the execution is undefined), the fun () execution of the resulting variable A cannot be freed ( Unless the function in F is freed), a closure is generated (the variable A is closed for use by F).

The key to generating closures is that a function B declared within function A is out of a, and the data generated within function A is used within the B function (declaration or by value).

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

The code is 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 is run, a closure is formed, and when no data is referenced outside the function, the closure has a short life cycle: The function is freed when it is executed.

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

The code is as follows:
function Fun () {

var a = 1;

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

}

var f1 = fun (); A closed package

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, each resulting in a closure, fun () executed once, and the variable declaration statement executed once. 10. Finally , say something about IE6 memory leaks and closures

In IE 6, a circular reference to a non-native JS object (DOM, etc.) can lead to a memory leak, which should be noted when using a closed packet if a non-JS native object reference is involved.

function Fun () {

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

node = null; Interrupting circular references to prevent memory leaks

Node holds DOM objects, DOM objects exist outside of fun (and always exist, even if deleted is only removed from the document tree), fun execution results in closures, and also forms a circular reference for DOM objects and callback functions (Node-function-node), in IE 6 A memory leak occurs under the

A summary of JavaScript functions and scopes

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.