JavaScript Advanced Programming Notes (VII)

Source: Internet
Author: User

function expression

Methods for defining functions:

function declaration:

function functionname (arg0, arg1, arg2) {

function body

}

Firefox, Safari, Chrome, and Opera define the Name property for the function whose value is equal to the identifier after the functions keyword.

function Promotion : Read the function declaration before executing the code.

Using function Expressions:

var functonname = function (arg0, arg1, arg2) {

function body

}

The function created is called an anonymous function , and the Name property is an empty string.

function expressions must be assigned before they are used.

First, recursion

A function is constructed by calling itself by name.

            var anotherfactorial = factorial;             NULL ;            Alert (Anotherfactorial (4));  // error!

When Anotherfactorial is called, an error occurs because the factorial must be executed and factorial is not a function.

Arguements.callee is a pointer to a running function that can be used to implement a recursive call to a function.

Arguements.callee cannot be accessed through scripting in strict mode, but can be implemented by means of a named function expression.

Second, closed package

Closures: Functions that have access to variables in another function scope.

The most common way to create closures is to create a function inside a function.

function Compare (value1, value2) {       if  (value1 < value2) {           return  -1 ;      }        if  (value1 > value2) {           return  1;      }       Else {         return 0;      }}

When compare () is called, an active object containing the arguemnets,value1,value2 is created. Each execution environment in the background has an object that represents a variable-the variable object. The variable object of the global environment always exists, and the variable object of the local environment of the Compare () function exists only in the process of the function execution. When you create the Compare () function, you pre-create a scope chain that contains the global variable object, which is stored in the internal [[Scope]]. When compare is called, an execution environment is created for the function, and the scope chain of the execution environment is built from the object of the [Scope] property of the copy function. The scope chain essence is a pointer to a variable object, referencing only the object that does not actually contain the variable.

After the Createcomparisonfunction () function is executed, its active object is not destroyed because the scope chain of the anonymous function is still referencing it, and after the anonymous function is destroyed, The active object of createcomparisonfunction () will not be destroyed.

// Create a function var compare = Createcomparisonfunction ("name"); // calling Functions var result = Compare ({name: "Nicholas"}, {name: "Greg"}); // to dismiss a call to an anonymous function null;

1. Closures and variables

Closures can only get the last value of any variable in the containing function. The closure holds the entire variable object,

  function createfunctions () {                varnew  Array ();                                  for (var i=0; i <; i++) {                    function() {                        return  i;                    };                }                                 return result;               }            

Each function's scope chain holds the active object of the Createfunctions () function, which refers to the same variable I, when the Createfunction () function returns, the value of the variable i is 10, and each function refers to the same variable object that holds the variable i.

                 for (var i=0; i < i++) {                    function(num)                        {returnfunction  () {                            return  num;                        };                    } (i);                }

Creates an anonymous function that assigns the result of the anonymous function immediately to the array. Because the function arguments are passed by value, the values of the I variable are copied to NUM, and a closure that accesses NUM is created and returned inside the anonymous function.

2. About this object

The execution environment of an anonymous function is global, and its this object usually points to window.

It is not possible to directly access these two variables of an external function until the intrinsic function searches for this and arguements only to its active object.

var name = "the window";                 var object = {            "My object",                    function() {                return  function() {                    returnthis. name;};}        ;

Storing the This object of an external scope in a variable that a closure can access allows the closure to access the object. Even after the function returns, that is a reference to object.

function () {                    varthis;                     return function () {                        return  that.name;                    };                }

3. Memory leaks

If the scope chain of a closure holds an HTML element, the element cannot be destroyed.

A variable is present by putting a copy of the element.id, and referencing the variable in the closure eliminates the circular reference. It is also necessary to set the element variable to null.

Iii. impersonation of block-level scopes

The variables defined in the block statement are created in the containing function rather than in the statement.

The same variable is declared multiple times in JavaScript, ignoring subsequent declarations.

Anonymous functions for private scopes :

(function() {      // block-level scope });

The function declaration is enclosed in parentheses to indicate that it is actually a function expression , and the next pair of parentheses immediately calls the function.

function (){}();    // Error

JavaScript takes the function keyword as the beginning of a declaration of functions, and cannot have parentheses after the function declaration. The function expression can be followed by parentheses.

You can use a private scope as long as you want some variables temporarily.

            function Outputnumbers (count) {                            (function  () {                    for (var i=0; i < count; i++) {                        alert (i);                    }                }) ();                                alert (i);    // error            }

Any variables defined in the anonymous function are destroyed at the end of execution. The private scope can access count because the anonymous function is a closure that can access all variables that contain scopes.

This technique is often used outside the function in the global scope, restricting the addition of too many variables and functions to the global scope.

Iv. Private variables

Any variable defined in a function can be considered a private variable. Private variables include arguments to functions, local variables, and other functions defined inside the function.

Privileged Methods : public methods that have access to private variables and private functions.

The

is defined in the constructor:

 function   MyObject () { //  private variables and private functions  var               privatevariable = 10;  function   Privatefunction () {return  false         //  Privileged method  this . Publicmethod = function   () {PRI           vatevariable  ++;        return   Privatefunction (); }}

The privileged method as a closure has access to all the variables and functions in the constructor.

            functionPerson (name) { This. GetName =function(){                    returnname; };
Privileged methods
This. SetName =function(value) {Name=value; }; } varperson =NewPerson ("Nicholas"); Alert (Person.getname ()); //"Nicholas"Person.setname ("Greg"); Alert (Person.getname ()); //"Greg"

1. Static private variables

Create a privileged method by defining a private variable or function in a private scope.

 (function   () {                                 var  name = "" ;                                    Person  = function   (value) {                                Name  = value;                                };                    Person.prototype.getName  = function   () {                 return   name;                                }; Person.prototype.setName  = function   (                Value) {Name  = value;            }; })();

Name becomes a static property that is shared by all instances. Calling SetName () on one instance affects all instances. Creating a person instance or calling SetName () will give the name instance a new value.

2. Module mode

The preceding pattern is used for custom types to create private variables and privileged methods.

Module mode creates private variables and privileged methods for a singleton .

Singleton : An object with only one instance.

This pattern is useful when you need to perform some initialization of a singleton, while maintaining its private variables.

            functionbasecomponent () {}functionothercomponent () {}varApplication =function(){                            //private variables and functions                varcomponents =NewArray (); //InitializeComponents.push (Newbasecomponent ()); //Public                return{getcomponentcount:function(){                        returncomponents.length; }, RegisterComponent:function(component) {if(typeofComponent = = "Object") {Components.push (component);            }                    }                };            }(); Application.registercomponent (Newothercomponent ());  Alert (Application.getcomponentcount ()); //2

This creates an object to manage the components. Both the Getcomponentcount method and the RegisterComponent method of the returned object have access to the components ' privileged methods.

If you must create an object and initialize it with some data, and expose some methods that can access these private variable data, you can use module mode so that each singleton created is an instance of object, because it is represented by the literal.

3. Enhanced Module mode

This enhanced module pattern is suitable for cases where the singleton must be of a certain type, while some properties and/or methods must be added to enhance it.

            varApplication =function(){                            //private variables and functions                varcomponents =NewArray (); //InitializeComponents.push (Newbasecomponent ()); //Create a local copy of the application                varApp =Newbasecomponent (); //public InterfaceApp.getcomponentcount =function(){                    returncomponents.length;                            }; App.registercomponent=function(component) {if(typeofComponent = = "Object") {Components.push (component);                            }                }; //return this copy                returnapp; }();

JavaScript Advanced Programming Notes (VII)

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.