preface

This series is in the process of learning JS to do reading notes, will be the key knowledge extraction out of leisure time to read, if you have read this book, that collection when review with; If you haven’t read this book, you can save it for later

Note: Excerpts or summaries from chapters 3-7 of JavaScript Advanced Programming


There are two ways to define a function: one is a function declaration, and the other is a function expression.

/ / the declarative
function fnName(arg0, arg1) {    
    / / the function body
} 

// Function expression
var fnName = function(arg0, arg1){    
    / / the function body
};
Copy the code

Function declaration promotion: the function declaration is read before the code is executed. This means that you can place a function declaration after the statement that calls it.

Anonymous functions: Functions created when function expressions are created are called anonymous functions because there is no identifier after the function keyword.

First, the recursive

Recursive functions are formed when a function calls itself by name.

Second, the closure

Closures are functions that have access to variables in the scope of another function.

When a function is called, an execution context and the corresponding chain of scopes are created. The activation object of the function is then initialized using arguments and the values of other named parameters. But in the scope chain, the active object of the outer function is always in the second place, and the active object of the outer function is in the third place… Up to the global execution environment as the end of the scope chain.

function compare(value1, value2){   
    if (value1 < value2){   
        return - 1;   
    } else if (value1 > value2){
        return 1;   
    } else {    
        return 0; }}var result = compare(5.10); 
Copy the code

A schematic of the scope chain generated during the above code execution:

When compare() is called, an active object with Arguments, Value1, and value2 is created. The variable object of the global execution environment (including Result and compare) is the second in the scope chain of the compare() execution environment.

When an anonymous function returns from the outer function, its scope chain is initialized to an active object and a global variable object containing the outer function. This allows anonymous functions to access variables defined in the outer function. After the outer function completes execution, the scope chain of its execution environment is destroyed, but its active object remains in memory until the anonymous function is destroyed.

Because closures carry the scope of the function that contains them, they take up more memory than other functions. Overuse of closures can lead to excessive memory usage.

1. Closures and variables

One notable side effect of this configuration mechanism for scoped chains is that closures can only take the last value of any variable in the containing function.

We can force the closure to behave as expected by creating another anonymous function

2. This object

  • The this object is bound at runtime based on the function’s execution environment: in a global function, this equals window, and when the function is called as a method of an object, this equals that object.

  • The execution environment of anonymous functions is global, so their this object usually points to window.

  • Each function automatically gets two special variables when called: this and arguments. The inner function searches for these two variables only up to its live object, so it is never possible to directly access the two variables in the outer function.

  • You can give closure access to this object by storing it in a variable accessible to the closure. The same goes for arguments.

3. Memory leaks

  • If a closure holds an HTML element in its scope chain, that means that element cannot be destroyed.

  • Set the Element variable to null. This allows the DOM object to be de-referenced, reducing its number of references and ensuring that its memory is properly reclaimed.

Imitate block-level scope

JavaScript has no concept of block-level scope. This means that variables defined in a block statement are actually created in the containing function rather than the statement.

So in JAVA, C++ and other languages, when a for loop is defined in a function, the I inside the loop is only valid, but in js, because it is created in a function, it can still be called elsewhere in the function.

Of course, the above situation is perfectly solved with Let after ES6.

  • JavaScript never tells you if you declared the same variable multiple times; In this case, it simply ignores subsequent declarations (it does, however, perform variable initialization in subsequent declarations).
  • JavaScript treats the function keyword as the start of a function declaration, which cannot be followed by parentheses.
  • Function expressions can be followed by parentheses. To convert a function declaration into a function expression, add a pair of parentheses.
  • This reduces the memory footprint of closures because there are no references to anonymous functions. As soon as the function completes execution, its scope chain can be destroyed immediately.

4. Private variables

  • Strictly speaking, there is no concept of private members in JavaScript; All object properties are public.
  • Any variables defined in a function are considered private because they cannot be accessed outside the function. Private variables include parameters of a function, local variables, and other functions defined inside the function.
  • A public method that has access to private variables and functions is called a privileged method. There are two ways to create privileged methods on objects. The first is to define privileged methods in constructors. The other is to implement privileged methods with static private variables.

Static private variables

  • Initializing an undeclared variable always creates a global variable. Assigning values to undeclared variables in strict mode results in an error.
  • Create global objects inside the function, define privileged methods in the manner of object prototypes, and since objects are global, they can be referenced anywhere.

2. Module mode

  • A singleton is an object that has only one instance. By convention, JavaScript creates singletons as object literals.
  • If you have to create an object and initialize it with some data, and expose some methods to access that private data, you can use the module pattern.
  • Singletons are usually present as global objects, and we do not pass them to a function. There is no need to use the instanceof operator to check its object type.

3. Enhanced module patterns

– This enhanced modular pattern is suitable for cases where singletons must be instances of a type and must be enhanced by adding attributes and/or methods.

var singleton = function(){  
    // Private variables and functions
    var privateVariable = 10;  
    function privateFunction(){
        return false;    
    }  
    // Create an object
    var object = new CustomType();  
    // Add privileges/public attributes and methods
    object.publicProperty = true;  
    object.publicMethod = function(){   
        privateVariable++;   
        return privateFunction();    
    };  
    // Return this object
    returnobject; } ();Copy the code

summary

Functional expressions are a very useful technique in JavaScript programming. Function expressions can be used to achieve dynamic programming without naming functions. Anonymous functions, also known as Ramda functions, are a powerful way to use JavaScript functions. The following summarizes the characteristics of functional expressions.

  • Function expressions are different from function declarations. Function declarations require names, but function expressions do not. Function expressions without names are also called anonymous functions.
  • Recursive functions become more complex when you cannot determine how to refer to them;
  • Recursive functions should always call themselves recursively using arguments.callee and do not use function names — they may change.

Closures are created when other functions are defined inside a function. Closures have access to all variables inside the containing function, as follows.

  • In a background execution environment, the scope chain of a closure contains its own scope, the scope of the containing function, and the global scope.
  • Normally, the scope of a function and all its variables are destroyed at the end of the function execution.
  • However, when a function returns a closure, the function’s scope is kept in memory until the closure does not exist.

You can use closures to mimic block-level scope in JavaScript (JavaScript itself has no concept of block-level scope), and here’s the gist.

  • Create and call a function immediately so that the code can be executed without leaving a reference to the function in memory.
  • The result is that all variables inside the function are immediately destroyed — unless some variable is assigned to a variable in the containing scope (that is, the outer scope).

Closures can also be used to create private variables in objects, as described below.

  • Even though there is no formal concept of private object properties in JavaScript, closures can be used to implement public methods that access variables defined in the include scope.
  • Public methods that have access to private variables are called privileged methods.
  • You can use the constructor pattern, the stereotype pattern to implement privileged methods of custom types, and you can use the module pattern, the enhanced module pattern to implement privileged methods of singletons.

Function expressions and closures in JavaScript are extremely useful features that allow you to do a lot of things with them. However, because you have to maintain additional scopes to create closures, overusing them can take up a lot of memory.

Congratulations on finishing this chapter! As the basic content of JS learning! That’s the end of this series of articles. I read it and it hit me! How about you? Ha ha ha! Keep it up!

Other chapters are linked below!

JavaScript Advanced Programming: Basic concepts of JS

JavaScript Advanced Programming: JS variables, scopes, and memory issues

JavaScript Advanced Programming: Reference type

JavaScript Advanced Programming: Object-oriented programming

JavaScript Advanced Programming: Functional expressions