10 JavaScript difficulties--excerpt

Source: Internet
Author: User
Tags closure

1. Execute functions immediately

Execute the function immediately, that is, immediately invoked function Expression (iife), just as its name is when the function is created and executed immediately. It does not bind any events, and it does not have to wait for any asynchronous operations:

function () {...} is an anonymous function that encloses its pair of parentheses and converts it to an expression, followed by a pair of parentheses that calls the function. Immediately executing a function can also be understood as calling an anonymous function immediately. The most common scenario for executing functions immediately is to limit the scope of the var variable to your function, which avoids naming conflicts.

2. Closures

For closures (closure), when an external function returns, the intrinsic function can still access the variables of the external function.

In the code, the external function F1 executes only once, the variable n is set to, and the intrinsic function F2 is assigned to the variable result. Since the external function F1 has been executed, its internal variable n should be purged in memory, but it is not true: every time we call result, we find that the variable n is always in memory and is accumulating. Why is it? This is the magic of closures!

3. Defining private variables with closures

Typically, JavaScript developers use underscores as a prefix for private variables. But in fact, these variables can still be accessed and modified, not the real private variables. In this case, a closure can be used to define a true private variable:

In the code, the Name property of the object P is a private property and cannot be accessed directly using P.name.

4. Prototype

Each JavaScript constructor has a prototype property that sets the properties and methods that all instance objects need to share. The prototype property cannot be enumerated. JavaScript only supports inheritance properties and methods through the prototype property.

In the code, x and Y are the object instances created by the constructor rectangle, which inherit the Getdimensions method through prototype.

5. Modular

JavaScript is not a modular programming language, at least ES6 before landing. For a complex web application, however, modular programming is a fundamental requirement. At this point, you can use the immediate execution function to achieve modularity, just as many JS libraries such as jquery and our fundebug are implemented.

Modularity is the control of the accessibility of properties and methods within the module, either private or public, as needed. In code, module is a stand-alone block, N is its private property, print is its private method, Decription is its public property, and add is its common method.

6. Variable Promotion

JavaScript moves all variables and function declarations to the front of its scope, which is called variable elevation (hoisting). In other words, wherever you declare variables and functions, the interpreter moves them to the front of the scope. So we can use variables and functions first and then declare them.

However, only variable declarations are promoted, and variable assignments are not promoted. If you don't understand this, sometimes it goes wrong:

The above code is equivalent to the following code:

To avoid bugs, developers should declare variables and functions at the beginning of each scope.

7. currying

Curry, or currying, can be a function that becomes more flexible. We can call it by passing in more than one parameter at a time, or you can just pass in a subset of the arguments to call it, and let it return a function to handle the remaining arguments.

Code, we can pass 2 1 as the parameter Add (1) (1) at a time, or we can get the ADD1 and ADD10 functions after passing in 1 parameters, which is very flexible to use.

8. Apply, call and bind methods

JavaScript developers need to understand the different points of the apply, call, and bind methods. What they have in common is that the first parameter is this, which is the context that the function relies on when it runs.

Of the three, the call method is the simplest, which is equivalent to specifying the this value to invoke the function:

The Apply method is similar to the call method. The only difference between the two is that the Apply method uses an array to specify the parameters, and each parameter of the call method needs to be specified individually:

Apply (Thisarg, [Argsarray])

Call (Thisarg, arg1, arg2, ...)

Using the Bind method, you can bind the this value to a function and then return as a new function:

9. memoization

Memoization is used to optimize more time-consuming calculations by caching the results in memory so that the same input values will only need to be read in memory the next time.

In the code, the 2nd calculation of Fibonacci (100) only requires that the results be read directly in memory.

10. Function overloading

The so-called function overloading (method overloading) is the same as the function name, but the input output is not the same. Alternatively, allow a function to have a variety of inputs, depending on the input, to return different results. Intuitively, a function overload can be implemented by if...else or switch, which is not a control. The father of jquery, John Resig, proposed a very ingenious (Bian) approach that took advantage of closures.

In effect, the Find method of the People object allows 3 different inputs: 0 parameters, returns the owner name, 1 parameters, finds the name of the person according to FirstName and returns, and 2 parameters, finds the name of the person and returns according to the full names.

The difficulty is that people.find can only bind a function, so why does it handle 3 different types of input? It is not possible to bind 3 functions at the same time Find0,find1 and Find2! The key here is the old property.

The order of calls by the Addmethod function shows that People.find eventually binds to the Find2 function. However, when you bind Find2, old is Find1, and, similarly, when you bind Find1, old is find0. 3 functions Find0,find1 and Find2 are chained together by closures.

According to the logic of Addmethod, when F.length does not match arguments.length, it will call old until the match is reached.

10 JavaScript difficulties--excerpt

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.