Function expression (JavaScript elevation note)

Source: Internet
Author: User

Function expression (JavaScript elevation note)
Function declaration features: function declaration is upgraded (before the code is executed, the parser reads the function declaration and makes it available before executing any code, meaning that the function declaration can be placed after the call Statement)

function functionName(arg0,arg1) {//do something}

 

Function expression features: no improvement (the parser will be parsed and executed only when it is executed in the code line where it is located) 1. Most Common-Anonymous Functions
Var functionName = function () {// do something}; 2. Name the function expression var functionName = (function f () {// do something });

 

1. recursion 1. arguments. callee a pointer to the function being executed, replacing the function name
function factorial(num) {if(num <= 1){return 1;} else {return num * arguments.callee(num-1);}}

 

2. An error is reported for arguments. callee in the strict mode of the naming function expression. It can be replaced by a naming function expression.
var factorial = (function f(num) {if(num <= 1){return 1;} else {return num * f(num-1);}});

 

2. Closure refers to the function that has the permission to access the variables in another function scope to create a closure. The most common way is to create another function within a function because the closure will carry the scope of the function that contains it., therefore, excessive use of closures may cause excessive memory usage. The closure can only obtain the last value containing any variable in the function (not very understandable)
// Error chestnut function createFunc () {var result = new Array (); for (var I = 0; I <10; I ++) {result [I] = function () {return I; // closure, all return the last value of I 10 };} return result ;}// the correct chestnut function createFunc () {var result = new Array (); for (var I = 0; I <10; I ++) {result [I] = function (num) {return function () {return num ;};} (I); // execute now and pass the current value to the num} return result;} parameter ;}

 

About this: the execution environment of anonymous functions is global. this usually points to windowIE9-: Memory leakage-if the scope chain of the closure stores an HTML element, the element cannot be destroyed.
// Error chestnut function asignHandler () {var element = document. getElementById ('someelem '); element. onclick = function = () {// closure alert (element. id) ;}}// the chestnut function asignHandler () {var element = document. getElementById ('someelem '); var id = element. id; // Save the copy element. onclick = function = () {// closure alert (id); // pop-up copy}; element = null; // unreference, recycle memory}

 

3. imitating the concept of block-level scope JavaScript with no block-level scope
// Function outputNumbers (count) {for (var I = 0; I <count; I ++) {// variable I in outputNumbers () in the scope) {(function () {// block-level scope, closure, accessible external variable for (var I = 0; I <count; I ++) {alert (I) ;}}) (); alert (I); // Error !} // Use: avoid global variables and functions. // no reference pointing to anonymous functions. Therefore, the memory occupied by closures can be reduced, once the function execution is complete, it can destroy its scope chain // put the following code in the global scope (function () {var now = new Date (); // now is the local variable of the anonymous function if (now. getMonth () = 0 & now. getDate () = 1) {alert ('Happy new year! ');}})();

 

Iv. Private variables and privileged methods 1. Defining privileged methods in constructors features: each instance creates the same set of new methods
Function Person (name) {// name is a private variable // two privileged methods this. getName () = function () {return name;}; this. setName () = function (value) {name = value ;};}

 

2. Define private variables and functions (static private variables) in private scopes. Features: private variables and functions are shared by each instance.
(Function () {var name = ''; // shared, static private variable, Person = function (value) {name = value ;}; Person. prototype. getName = function () {return name;}; Person. prototype. setName = function (value) {name = value; // calling setName () on an instance will affect the name of all instances };})();

 

3. The module mode creates private variables and privileged methods for a single instance (only one instance object). This method is applicable to scenarios where you need to initialize some data of the single instance and maintain its private variables.
Ar application = function () {// Private variable and function var components = new Array (); // initialize component. push (new BaseComponent (); // Add a BaseComponent (irrelevant) new instance to the array // privileged method return {getComponentCount: function () {return components. length ;}, registerComponent: function (component) {if (typeof component = 'object') {components. push (component );}}};}();

 

4. enhance the module mode (not easy to understand, understand, and then add) in other chapters of this book, use the function name without parentheses to access the function pointer instead of calling the function! 1. the return function stops and exits immediately after the return statement is executed. Therefore, any code after the return statement will never execute the return statement or return a value, after the function is stopped, undefined 2 is returned. in a parameter function, you can use the arguments object (one of the two special objects of the function) to access the parameter Array (but arguments is not an Array instance ), you can use arguments together with the named parameters and the memory space of the corresponding named parameters are independent, but their values will be synchronized. parameters that do not have to name unpassed values will be automatically assigned to undefinedarguments. callee: A pointer pointing to a function that owns the arguments object (tightly coupled) 4. this (one of the two special objects of the function) references the environment object where the function data is executed. 3. two functions with the same name are not reloaded. The name belongs to the function defined later. 4. the function name in the ECMAscript function as a value is itself a variable, so the function can be used as a value-you can pass a function to another function like a parameter (without parentheses) -One function can be returned as the result of another function. the internal attribute of the function. The caller attribute of the arguments object this object points to the function that calls the current function. If the current function is called globally, the value is null. You can use arguments. callee. caller achieves loose coupling 6. function attribute and method length attribute: indicates the number of name parameters that the function wants to accept. prototype attribute: ECMAscript5 cannot be enumerated * method for setting the value of this, extended Function scope (non-inherited method)-apply (scope, [parameter])-call (scope, parameter 1, parameter 2, parameter 3) bind (): create an instance and bind this value to the bind () parameter * Inheritance Method toLocaleString (), toString (), valueOf () and above all return the function code

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.