JavaScript function Detailed _ Basics

Source: Internet
Author: User
Tags anonymous closure eval generator tagname

Brief introduction

In many traditional languages (c/c++/java/c#, etc.), functions are present as a second-class citizen, you can only declare a function with the keyword of the language and call it, if you need to pass the function as an argument to another function, or assign to a local variable, or as a return value, We need to go through some special ways such as function pointer, Agent (delegate) and so on.
In the JavaScript world, a function is a first-class citizen, and it has not only the use of all the traditional functions (declarations and calls), but also can be done like a simple value assignment, argument, return, such functions are also called the first-level functions (first-class function). Not only that, functions in JavaScript also act as constructors for classes, but also as instances of function classes (instance). Such multiple identities make JavaScript functions very important.

First, JavaScript function entry level

JavaScript functions, like the general language, follow the principle of first declaration, which can contain only letters, numbers, underscores, or $, and cannot begin with a number. The following two types of declarative methods are common to functions:

Copy Code code as follows:

Direct declaration Function MyFunc
function MyFunc (/* arguments * *) {
}

Assigning anonymous functions to local variables MyFunc
var myfunc = function (///* arguments * *) {
}

Note that there are subtle differences between the two types of function declaration methods: The first is a named function when declared, whether it is declared before, after, or even after the call (for example, after a return statement or a branch that will never be true), which is accessible throughout the scope The second way is by assigning the anonymous function to the variable, which is strictly not a function declaration (a functional expression) but a function expression (function), which cannot be accessed by any code until the assignment is made. That is, the assignment must be completed before the call, or the error will occur when invoked: "typeerror:undefined is not a function". For example:

Copy Code code as follows:

Myfunc1 (); Can be called normally, because Myfunc1 adopts the way of direct declaration

function Myfunc1 () {
}

MYFUNC2 (); Error typeerror:undefined is not a function

var myfunc2 = function () {
};


The basic invocation of a function is called by a pair of parentheses, the same as a traditional language: MyFunc (). JavaScript functions also support direct or indirect recursive (recursive) calls, such as the classic Fibonacci function that can be implemented with javascript:

Copy Code code as follows:

function fib (n) {
if (n = = 1 | | n = = 2) {
return 1;
} else {
return fib (n-2) + fib (n-1);
}
}

Functions in JavaScript can handle variable-length arguments, and within functions there is a local variable named arguments, which is an object of an array of classes (array-liked) that contains all the arguments passed in the call, with the length attribute representing the number of parameters. For example:

Copy Code code as follows:

function Test () {
alert (arguments.length);
}

Test (1); 1
Test (1, ' a '); 2
Test (true, [], {}); 3 The use of arguments can be similar to the C language printf functions, can also be used to implement the method polymorphism.

Second, JavaScript function advanced

2.1 Anonymous functions and nested functions

In JavaScript you can declare a function that has no name, called an anonymous function (AnonyMouse function). JavaScript also allows you to declare functions inside functions, called nested functions (Nested function), and nested functions are scoped to the entire parent function.

A use of anonymous functions and nested functions is seen in the section of the previous function declaration, because anonymous functions do not have names, do not introduce new variables to pollute the context, and bring new variable scopes, so anonymous functions are often used to prevent global environmental pollution.

JavaScript runtime has a special global environment (global object), which holds the global functions and variables, the actual development of a number of third-party libraries or multiple JS files, if not careful to introduce duplicate variables or function declarations in the global object, Can cause code execution confusion. For example, the introduction of two JS files, respectively defining their own function log as internal use, then the second introduced function will overwrite the first definition and will not throw any errors, in subsequent execution, call log function may cause errors. At this time using an anonymous function to the entire JS logic packaging, you can avoid this error, this method has been most open source JS library use.

Copy Code code as follows:

(function () {//anonymous function

function log (msg) {
Console.log (msg);
}

Other code

}()); Execute now

The above code is a simple example where the scope of the log function is limited to the anonymous function, and the anonymous function is included in a pair of parentheses () to form a function expression, and the value of the expression is a function, followed by a pair of parentheses that immediately executes the function. Let the original code run normally once. However, the functions declared in this manner, variables declared through Var, and so on, are internal and cannot be accessed by any code other than the anonymous function. If you need to expose some functions as interfaces, there are several ways to do this:

Copy Code code as follows:

var mylib = (function (global) {

function log (msg) {
Console.log (msg);
}

Log1 = log; Method One: Make use of the default behavior of variable declaration without VAR, become global variable in LOG1 (not recommended)

GLOBAL.LOG2 = log; Method Two: Add the Log2 property directly on the global object and assign the value to log function (recommended)

return {//Law III: Returns via anonymous function is worth to a series of interface function collection objects, assigned to the global variable Mylib (recommended)
Log:log
};

} (window));

2.2 Higher-order functions (High-order function)

If a function is used as a parameter or a return value, it is called a high-order function, and functions in JavaScript can be used as higher-order functions, which is also characteristic of the first class of functions. Let's analyze the two ways of using them separately.

Copy Code code as follows:

function negative (n) {
Return-n; Take the opposite value of n
}

function square (n) {
return n*n; The square of N
}

function process (Nums, callback) {
var result = [];

for (var i = 0, length = nums.length i < length; i++) {
Result[i] = callback (nums[i]); All elements in an array nums are passed to callback for processing, saving the return value as the result
}

return result;
}

var nums = [-3,-2,-1, 0, 1, 2, 3, 4];
var N_neg = Process (nums, negative);
N_neg = [3, 2, 1, 0,-1,-2,-3,-4];
var n_square = Process (nums, square);
N_square = [9, 4, 1, 0, 1, 4, 9, 16];

The above code shows an example of passing a function as an argument to another function process call, in the implementation of the process function, to treat callback as a black box, to pass the parameter to it, and then to get the return value, which is not clear about the specific implementation of the callback before the call. Only when executing to lines 20 and 22, does callback represent negative or square, respectively, to take the opposite or square value of each element.

Copy Code code as follows:

function Generator () {
var i = 0;
return function () {
return i++;
};
}

var gen1 = generator (); Get a natural number generator
var Gen2 = generator (); Get another natural number generator
var r1 = Gen1 (); R1 = 0
var r2 = Gen1 (); r2 = 1
var r3 = Gen2 (); R3 = 0
var r4 = Gen2 (); R4 = 1

The above code shows an example of a function as a return value, generator is a natural number generator function, and the return value is a natural number generating function. An anonymous function is returned as a result each time the generator is invoked, and the anonymous function returns each natural number, in turn, when it is actually called. The variable i in generator will increase by 1 each time the anonymous function is invoked, which is actually a closure. Let's introduce the closure.


2.3 Closure (Closure)
Closures (Closure) are not a new concept, and closures are used in many functional languages. In JavaScript, a closure is used when you use variables in the scope of an external function in an inline function. Use a common analogy to explain the relationship between closure and Class (Class): Classes are data with functions, and closures are functions with data.
The variables used in closures have an attribute, that is, they are not released when the parent function returns, but end with the closure life cycle. For example, as in the example in the previous section, Gen1 and Gen2 use separate variable i (when Gen1 I generator 1, Gen2 I is not affected, and vice versa), as long as GEN1 or gen2 these two variables are not garbage collected by JavaScript engine , their respective variable I will not be released. In JavaScript programming, the closure is used unconsciously, and the feature of closure is easy to bring to the memory leak. For example:

Copy Code code as follows:

var elem = document.getElementById (' test ');
Elem.addeventlistener (' click ', function () {
Alert (' You clicked ' + Elem.tagname);
});

The function of this code is to click a node to display its label name, it will register an anonymous function as a DOM node click event handler function, the function refers to a DOM object Elem, forming a closure. This produces a circular reference, the:dom-> closure->dom-> closure ... The DOM object is not freed until the closure is released, and the closure is present as an event handler for the DOM object, so the closure is not released until the DOM object is released, and even if the DOM object is removed in DOM tree, the DOM object and the closure are not freed because of the existence of the circular reference. You can avoid this memory leak in the following ways:

Copy Code code as follows:

var elem = document.getElementById (' test ');
Elem.addeventlistener (' click ', function () {
Alert (' You clicked ' + This.tagname); No longer directly referencing Elem variables
});

The above code uses this instead of elem (the this pointer in the DOM event handler is pointing to the DOM element itself), so that JS runtime no longer believes that the parent class's variables are used in the function, so the closure is no longer formed.
Closures also bring a lot of similar memory leaks, and only focus on closures when writing code, and try to avoid such problems.

2.4 class constructors
JavaScript functions are also constructors of classes, so you can use the New keyword to create an instance of a class as long as you declare a function.

Copy Code code as follows:

function person (name) {
THIS.name = name;
this.tostring = function () {
Return ' Hello, ' + this.name + '! ';
};
}

var p = new Person (' Ghostheaven ');
Alert (p); Hello, ghostheaven!. In the above instance, the person function is used as the constructor of the class, and this point points to the newly created instance object, which adds properties and methods to the instance, which can be referenced for detailed object-oriented JavaScript programming. What I want to say here is that a JavaScript function is a return value problem when used as a class constructor.

Copy Code code as follows:

function MyClass (name) {
THIS.name = name;
return name; The return value of the constructor?
}

var obj1 = new MyClass (' foo ');
var obj2 = MyClass (' foo ');
var obj3 = new MyClass ({});
var obj4 = MyClass ({});

The above constructor is more special, there is a return statement, then Obj1~obj4 point to what object? The actual result is this:

Copy Code code as follows:

Obj1 = MyClass Object
obj2 = ' foo '
Obj3 = {}
Obj4 = {}

The specific reason for this article is explained, this article no longer repeat, because the constructor with the return value will produce strange results, so do not call the return statement with the return value in the constructor (null returns CAN).

Three, JavaScript function monster class

Welcome to the Monster class function teaching area, here will give you how calm and comfortable to face the old strange ...

3.1 function Class
In the JavaScript runtime, there is a built-in class called function, and declaring a function with the functions keyword is actually a shorthand form for creating function class objects, all of which have all methods of the function class, such as call, apply , bind, and so on, you can verify this by instanceof the keyword.
Since a function is a class, its constructor is a function (which is itself an object of the function Class), and it should be possible to generate a functional object from the New keyword. The first monster is here, and that is how to construct a function with the functions class. The syntax for a function is as follows:

Copy Code code as follows:

New Function ([arg1[, arg2[, ... argn]],] functionbody)

Among them arg1, arg2, ... argn is a string, representing the parameter name, Functionbody is also a string, representing the function body, the previous parameter name can be much less, the function constructor will take the last parameter as the function body, the front is treated as a parameter.

Copy Code code as follows:

var func1 = new Function (' name ', ' Return "Hello," + name + "!"; ');
Func1 (' Ghostheaven '); Hello, ghostheaven!.

The above method constructs a function with function that is exactly the same as other functions declared with the functional keyword.
Seeing here, many people may ask why such a monster is needed. "Existence is reasonable", function class has its unique purpose, you can use it to dynamically generate a variety of function logic, or to replace the Eval function, and to maintain the current environment will not be contaminated *.


3.2 Self-updating functions (self-update function)
In many languages, a function cannot declare a function of the same name once it has been declared, or a syntax error occurs, and a function in JavaScript can not only repeat the declaration but also update itself. Eat your own monster!

Copy Code code as follows:

function SelfUpdate () {
Window.selfupdate = function () {
Alert (' second run! ');
};

Alert (' The ' run! ');
}

SelfUpdate (); The run!
SelfUpdate (); Second run! This function can be used for logic that runs only once, replacing the whole with a new logic after the first run.

Summary

The function of JavaScript is often powerful, and it also brings many negative problems while solving many problems beautifully. Monster-level function usage is usually a little-known usage, unless it is especially necessary not to use easily, otherwise it will cause code reading difficulties, affect team development efficiency.

* Strict mode is introduced in the new ECMAScript, the Eval function is greatly restricted in strict mode, and it can ensure the environment is not polluted

Small partners see understand not, very practical it, if there are missing places, but also ask the Great God to guide, common progress

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.