The function of the JavaScript

Source: Internet
Author: User
Tags types of functions

This is the second blog, the road is very long, I just started.

Almost everything in JavaScript is object, and the function is no exception. The function, however, is not just packing a bunch of attributes together, but the functions are the core of the language. To understand its core, we have to start with the basics.

First, the code block in JavaScript

To understand JavaScript functions, you need to understand the block of code first. The code blocks of JavaScript simply combine the statements together. The code block ends with the opening curly brace "{" At the beginning of the closing brace "}". In short, blocks of code let the statements in curly braces execute together. Code blocks are the most basic control structures in JavaScript. Here are some examples of JavaScript code blocks:

//Immediately invoked function expression;!function () {   varTriumph =false, Cake=false, Satisfaction= 0, Islie, note; //Block used as part of a function expression   varIslie =function(val) {returnval = = =false; }   //Block used as part of a conditional statement   if(Islie (cake)) {Triumph=true; Makenote (' Huge success '); Satisfaction+ = 10; }   //Block used as part of a function declaration   functionmakenote (message) {Note=message; }}();

As you can see, the function is essentially a named block of code that a developer could invoke. As an example:

// The inline conditional block statement is executed only once per cycle. if (Islie (cake)) {   ...} function makenote (message) {   ...} // The function declaration is executed as many times as it is called. Makenote ("moderate Success"); Makenote ("Huge Success");

1. Function parameters

You can initialize parameters such as control statements (If,for,while ...) by passing arguments into the function body. ) function. In JavaScript, a variable is either a composite type (such as an object, an array), or a primitive type (such as a string, an integer). When a composite type makes a parameter, it is passed to the function body by reference, and JavaScript passes a pointer to the position of the variable in the memory heap, not a copy of the variable. Conversely, when a basic type is communicated to a function, JavaScript is passed by value. This difference can lead to subtle bugs, because functions are often used as a conceptual black box, and people tend to assume that a function returns a variable only to affect the enclosing scope. When passed by reference, the Parameter object may be modified even if the function does not return a value. Here is an example of passing by reference and passing by value:

varObject = {             ' foo ': ' Bar '}, Num= 1; //Passed by reference passing by reference;!function(obj) {Obj.foo= ' Baz ';       } (object); //= = Object {foo: "Baz"}Console.log (object); //Passed by Value       ;!function(num) {num= 2;       } (num); //= 1Console.log (num);

(1) Parameter Object-arguments

Parameter objects apply to functions that do not require the number of parameters to be specified in advance. A Parameter object, like a wildcard, can traverse a parameter object like an array to access any number of arguments. Like what:

var function () {            var len = arguments.length,                = 0;              for (var x = 0; x < len; + +)                {+ = arguments[x];            }             return Total ;        };         // = 6        Console.log (SUM (1, 2, 3));

The parameter object, however, is just a bit like an array, and if you rewrite the script with more array methods, it will produce an error:

var function () {               var len = arguments.length,                   = 0;                 while (Arguments.length > 0) {                   + = arguments.pop ()               ;                   } return Total ;        };         // uncaught TypeError:arguments.pop is not a function        SUM (1, 2, 3);

Fortunately, ECMAScript 6 improves the way function parameters are used, and it is seldom necessary to use the original Parameter object. We can look at several new features added to the parameters.

(2) Default parameters (ECMAScript 6)

Many programming languages allow you to select a default value for a parameter in a function signature. JavaScript supports this feature in ECMAScript 6.

varJoin =function(foo = ' foo ', Baz = (foo = = = ' foo ')? Join (foo + "!"): ' Baz ') {            returnFoo + ":" +Baz; }        //= Hi:thereConsole.log (Join ("HI", "there")); //Use the default parameter if not supplied        //= Hi:bazConsole.log (Join ("HI")); //Use the default parameter if undefined is supplied        //= Foo:thereConsole.log (Join (Undefined, "there"))); //Use an expression which have access to the current set of arguments        //= Foo:foo!:bazConsole.log (Join (' foo '));

(3) Rest parameter Rest (ECMAScript 6)

Sometimes a function needs to support any number of arguments, but it can be cumbersome to do it with a parametric object.

1  varDispatcher = {2Joinfunction(before, after) {3                 returnBefore + ': ' + After4             },5Sumfunction () {6                 varargs =Array.prototype.slice.call (arguments);7                 returnArgs.reduce (function(Previousvalue, CurrentValue, index, array) {8                     returnPreviousvalue +CurrentValue;9                 });Ten             } One         } A         varProxy = { -Relayfunction(method) { -                 varargs; theargs = Array.prototype.splice.call (arguments, 1); -                 returndispatcher[method].apply (Dispatcher, args); -             } -         }; +         //= Bar:baz -Console.log (Proxy.relay (' Join ', ' bar ', ' Baz '))); +         // About AConsole.log (Proxy.relay (' Sum ', 1, 2, 3, 4, 5, 6, 7));

In the previous example, our proxy object expects a parameter, which is invoked as a method on dispatcher. It does not know how many other arguments are required when this function is called. To know that the parameter object is not an array, there is no method such as Splice,map or reduce. In order to pass any number of arguments left to dispatcher, you must use an array to handle them.

With the rest of the parameters rest, you don't have to deal with functions like a cipher. Here, rest of the rest is used to override the previous method:

varDispatcher ={join:function(before, after) {returnBefore + ":" +After }, sum:function(... rest) {returnRest.reduce (function(Previousvalue, CurrentValue, index, array) {returnPreviousvalue +CurrentValue;            });        }        }; varProxy ={relay:function(method, ... goodies) {returndispatcher[method].apply (dispatcher, goodies);        }        }; //= Bar:bazConsole.log (Proxy.relay (' Join ', ' bar ', ' Baz '))); // AboutConsole.log (Proxy.relay (' Sum ', 1, 2, 3, 4, 5, 6, 7));

2. Types of functions

Now that you have a better understanding of code blocks and parameters, let's drill down to function declarations and function expressions to see how these two types of functions are used in JavaScript. If you don't look closely, the two may be very similar.

// Function Declaration function Islie (cake) {   returntrue;} // Function Expression var function (cake) {   returntrue;}

The only difference between the two occurs during the assignment. The interpreter can access the function declaration during parsing. The function expression is part of the assignment expression and cannot be executed until the entire program assignment is complete. This difference looks small, but it has a big impact. Consider this scenario:

// = = Hi, I ' m a function declaration!         Declaration ();         function declaration () {            console.log ("Hi, I ' m a function declaration!" );        }         // = uncaught typeerror:expression is not a function         expression ();         var function () {            console.log ("Hi, I ' m a function expression!" );        }

As you can see in the previous example, the function expression throws an exception when it is called, but the function declaration executes normally. This exception reveals the key differences between function declarations and function expressions. JavaScript can understand the declared function and can parse the function before the program executes. Therefore, the invocation of the function does not matter before and after the declaration, because JavaScript has promoted the function to the top of the current scope behind the scenes. The function expression is not evaluated until the variable is assigned, so it is still undefined when it is called. So a good code style should define all the variables at the top of the current scope. In doing so, the order of the scripts is the same as the order of the JavaScript syntax parsing.

The previous concept was omitted, and when parsing the syntax, JavaScript would move all function declarations to the top of the current scope. So declarative functions can be placed anywhere in the script. To further explore the differences between declarations and expressions, take a look at this example:

function Sayhi () {            console.log ("HI");        }         var function Sayhi () {            console.log ("Hello");        }         // = = Hello         hi ();         // = Hi        Sayhi ();

When you look at this code, you might think that the function declaration will crash because it has the same name as the function expression. However, because the second function is part of the assignment variable and has its own scope, JavaScript treats them as different entities.

The function of the JavaScript

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.