For more information, see the JavaScript function v 0.5.

Source: Internet
Author: User

What is a function? A function is a set of statements and a basic module unit of JavaScript. It is used for code reuse, information hiding, and combined calling. The default return value of the function is undefined. The function is used to specify the behavior of an object (as the object method ). The function is an object! An object is a set of "key/value" pairs and has a "Pointer" connected to the prototype object ". (Objects generated by the Object literal are connected to the Object. prototype, Function object connected to Function. prototype ]. When a function is created, two hidden attributes are appended: the context of the function (this) and the code that implements the function behavior (when the JavaScript function is called, that is, the "call" attribute of the function is called, which is unique in the function and can be called.) because the function is an object, therefore, a function can appear anywhere in an object (stored in variables, arrays, and objects). It can also be passed as a parameter to other functions, or as a return value of other functions. In addition, functions can also have methods. Function literal (function expression): 1 // create a variable named "add" and assign values to the functions that add two numbers. 2 var add = function/* optional name */(a, B) {3 return a + B; 4 }; // note that the semicolon function literal at the end can appear anywhere where expressions are allowed, or be defined in other functions. The function literal contains four parts: The first part is the reserved word function. The second part is the function name (optional. It is mainly used for function recursion (it is easy to understand that a function uses its name to call itself recursively). It can also be used by debuggers and development tools to identify functions. If a function is not named, it is called an anonymous function. The third part is a set of parameters enclosed in parentheses. Multiple parameters are separated by commas ). The parameter name is defined as a function variable. Unlike normal variables that are initialized as undefined, they are initialized as values of real parameters when a function is called. The fourth part is a set of statements enclosed in curly braces. It is the topic of a function and is executed when the function is called. Tips: the difference between a function literal (a function expression) and a function declaration: The JavaScript parser first reads the function declaration and makes it available before executing any code (the function declaration is upgraded ); as for the function expression, it can be interpreted and executed only when the parser executes the code line to which it is located. Example: copy the code alert (add (2, 3); // 5 function add (a, B) {return a + B ;} // function declaration escalation // ====== for convenience, I wrote it together. During the test, do not execute ====================== alert (add (2, 3) in a single scope; // errorvar add = function (, b) {return a + B ;}; // function literal. Pay attention to the semicolon at the end (details are important ). Copy the Code. In addition, functions cannot be declared in if while for or other code blocks (specifically function declaration ), however, the function literal can appear in the above code block. Finally, if the function has a function name, the function name is not available externally. Example: var add = function add1 (a, B) {return a + B ;}; add (2, 3); // return 5add1 (3, 4); // ReferenceError: when the add1 is not defined function calls a function, in addition to the formal parameters defined during declaration, each function also receives two additional parameters: this and arguments. The value of this depends on the call mode (the initialization of this varies with the mode ). There are 4 call modes in JavaScript: method call mode function call mode constructor call mode (constructor call) call () and apply () the call operator in the indirect call mode is a pair of parentheses (what a concise statement) following any expression that generates function values ). Parentheses can contain zero or multiple expressions separated by commas. Each expression generates a parameter value. Each parameter value is assigned a formal parameter defined during function declaration. JavaScript does not check the number and type of parameters of a function. When the number of real parameters does not match the number of parameters, it does not cause a running error. If there are too many arguments, the excess parameters will be ignored. If there are too few, the missing value will be replaced with undefined. Method call mode when a function is saved as an attribute of an object, it is a method of the object. When a method is called, this is bound to this object. You can call a method by using a dot expression or subscript expression. Copy the code // create a myObject object, which has a value attribute and an increment method // The increment method receives an optional parameter. If the parameter is not a number, the number 1 var myObject = {value: 0, increment: fucntion (inc) {this. value + = typeof inc === 'number '? Inc: 1 ;}}; myObject. increment ('job'); // 1 myObject ["increment"] (3) is recommended; // 4 copy code function call mode when a function is not an object attribute, it is called as a function: var sum = add (5, 6); // The value of sum is 11 in this mode, this value is bound to a global object (this object is a window object in most browsers). If the constructor calls this value with the new Keyword before a function, A new object of the prototype member connected to the function will be created in the background. At the same time, this will be bound to the new object. Copy the code // create a constructor named Person, which constructs an object with name and age var Person = function (name, age) {this. name = name; this. age = age ;}; // provide the getName () and getAge () Methods to all the Person instances (that is, the prototype. prototype. getName = function () {return this. name;}; Person. prototype. getAge = function () {return this. age ;}; // construct a Person instance and test var tony = new Person ('Tony ', 23); console. log ('name: '+ tony. getName () + '\ nage:' + tony. getAg E (); copy the code to a function. If you create a function that is called with the new prefix, it is called the constructor function according to the conventions (just conventions, however, conventions are more important than configuration ideas. The first letter should be capitalized, so as to avoid errors such as the loss of new or new common functions during calls. Indirect call mode JavaScript is a functional object-oriented programming language. Since a function is an object, it can have methods. The call () and apply () methods can be used to call functions indirectly. The first parameter of the two methods can bind the this value of the function. Their syntax is as follows: call ([thisObj [, arg1 [, arg2 [,[,. argN]) // thisObj is the object to be bound to this, followed by the comma-separated parameter apply ([thisObj, [arglist]) // thisObj is the object to be bound to this, followed by parameters in the form of a list. Example: copy the code and declare a function var add = function (a, B) {return a + B ;}; // construct an array containing two numbers var arr = [5, 6]; // ==== add them through apply and call === var sum0 = add. apply (null, arr); var sum1 = add. call (null, arr [0], arr [1]); console. log (sum0); console. log (sum1); when the parameters and return values of the copy code function call the function, in addition to the hidden this parameter, there is also the arguments parameter, which is an object similar to an array. Arguments has a length attribute, but it does not have any array method. The function can use this parameter to access all parameters passed to the function. Copy the code // define a sum function, which adds all the parameters and returns the sum of the values var sum = function (/* but it is useless */) {var sum = 0; for (var I = 0; I <arguments. length; ++ I) {sum + = arguments [I];} return sum;}; console. log (sum (, 7); copy the code to see the example above. If we do not perform type detection for input parameters, when not all input parameters are of the Number type, the results will be unpredictable. Therefore, we need to transform the sum function so that it can detect errors. Copy the code // define a sum function, which adds all the parameters and returns the sum of the values var sum = function (/* but it is useless */) {var sum = 0; for (var I = 0; I <arguments. length; ++ I) {if (typeof arguments [I]! = 'Number') {throw {name: 'typeerror', message: 'sum needs numbers '};} sum + = arguments [I];} return sum ;}; console. log (sum (1, 2, 3, 4, 5, 6, 7); try {console. log (sum (1, 2, 'three ', '4');} catch (e) {console. log (e. name + ':' + e. message); // TypeError: sum needs numbers} When a function is called, it is executed from the first sentence and ended when the function body is closed. However, the return statement can be used to make the function return in advance. A function always returns a value. If no return value is specified, undefined is returned. If the new prefix is added before the function call and the returned value is not an object, this (the new object) is returned ). The extended type function JavaScript allows expansion of the basic types of languages. By adding methods to prototype, you can expand the functions of this type of object. This method applies to functions, arrays, strings, numbers, regular expressions, and boolean values. Example: copy the code // Add a method to Function. prototype to make this method available to all functions if (! Function. prototype. hasOwnProperty ('method') {// checks whether the Function prototype has the method property Function. prototype. method = function (/* String */name,/* function */func) {// check whether the parameter complies with the standard if (typeof name! = 'String' | typeof func! = 'Function') {// throw an exception. I will not go into details here} // second, check whether the name already exists in the prototype. If (! This. prototype [name]) {// throw an exception. I will not go into details.} This. prototype [name] = func; return this ;};} the copy code above provides a complete example of how to expand the type Function. add a method for prototype. You do not need to type prototype next time you add a method for the object. First, determine whether the method already exists in the prototype, and then register the method to the prototype. In the function, first check whether the parameter is valid, and then check that the name function already exists in the prototype. The following describes how to register a method to the Number prototype using the method (the Number registration method is similar to the Function method ). Number. method ('integer ', function () {return Math [this <0? 'Ceil ': 'floor'] (this) ;}); recursive functions are called directly or indirectly, it breaks down a problem into a group of similar subproblems, each of which is solved with an ordinary solution (obvious solution. Recursive functions can operate the tree structure very efficiently. Use recursive functions to calculate the factorial of a number (see the JS advanced programming 3 p177): copy the code function factorial (num) {if (num <= 1) {return 1 ;} else {return num * factorial (num-1) ;}} copy the code. Although the function looks okay on the surface, the following code can cause an error. Var anotherFactorial = factorial; factorial = null; alert (anotherFactorial (5); // error! When you set factorial to null and execute anotherFactorial (5), because factorial () must be executed, and factorial is no longer a function, an error occurs. So how can we write robust recursive functions? Method 1: Remember the arguments object. This object has a callee attribute pointing to the pointer of the function being executed, so you can use it to implement recursive calls to the function. Copy the code function factorial (num) {if (num <= 1) {return 1;} else {return num * arguments. callee (num-1) ;}} copy code method 2 (recommended): In strict mode (what is a strict mode ?) You cannot use a script to access arguments. callee. Accessing this attribute may cause errors. However, you can use the function literal (named function expression: it is just a function expression without omitting the function name .) To achieve the same result. Copy the code var factorial = (function fact (num) {// function name fact in external access is undefined if (num <= 1) {return 1 ;} else {return num * fact (num-1) ;}}); copy the code closure. before talking about the closure, let's briefly talk about the JavaScript scope. JavaScript does not support block-level scope. If (true) {var a = 1; console. log (a); // 1} console. log (a); // 1 JavaScript does have a function scope, which means that the parameters and variables defined in the function are invisible outside the function, variables defined in any position inside a function are visible anywhere inside the function. Because JS lacks block-level scope, it is best to declare all variables that may be used at the top of the function body. The benefit of the scope is that internal functions can access the parameters and variables that define their external functions (except this and arguments: assign this and arguments to other variables, which can be indirectly accessed .) Better yet, internal functions have a longer declaration cycle than their external functions. Copy the code var myObj = (function () {var value = 0; return {increment: function (inc) {value + = typeof inc = 'number '? Inc: 1 ;}, getValue: function () {return value ;}}(); copy the variable value defined in The anonymous function with the most external code, and return the objects with two methods. These methods continue to enjoy the privilege to access the value variable. This object cannot be modified by using two methods. The two methods (functions) can access the context when they are created. This is called a closure. A closure is a function that has the right to access variables in another function scope. It is important to understand the actual variables that internal functions (nested functions) can access external functions without having to copy them. The following example illustrates how to copy code // a bad example // construct a function and set an event handler for nodes in an array in an incorrect way. // When you click a node, as expected, a dialog box should be displayed showing the node sequence number, // but it will always show the number of nodes var add_the_handlers = function (nodes) {var I; for (I = 0; I <nodes. length; ++ I) {nodes [I]. onclick = function (e) {alert (I) ;}}; // for each event processing function, a dialog box is displayed, showing the number of nodes. length replication code this function is intended to pass a unique value (I) to each event processor, but it fails to achieve the goal because the event processor is bound to the variable I itself, instead of the value of variable I during function construction. (Understand? If you don't understand it, let's look at the next example. Copy the code // improved example // construct a function and set the event handler for the node in the array in the correct way, // click a node. A dialog box is displayed, showing the node sequence number. Var add_the_handlers = function (nodes) {var I; var helper = function (I) {return function (e) {alert (I) ;}; for (I = 0; I <nodes. length; ++ I) {nodes [I]. onclick = helper (I) ;}}; copy the code to avoid creating a function in the loop. First, create an auxiliary function outside the loop, let this helper function return another function bound to the current I value. The module mode can be constructed using functions and closures. A module is a function or object that provides interfaces but hides the state and implementation. By using a function to generate a module, you can almost discard global variables. The general form of the module mode is: a function that defines private variables and functions; a closure is used to create a privileged function that can access private variables and functions; finally, this privileged function is returned, or save them to an accessible place (in a variable, array, or object ). Using the module mode can discard the use of global variables and promote information hiding and other excellent design practices. The module mode is very effective for application encapsulation or other Singleton objects. The module mode can be used to generate security objects. Suppose you want to construct an object that generates serial numbers: copy the code var serial_maker = function () {// returns an object used to generate a unique string // a unique string consists of two parts: prefix + Serial Number // This object contains a method to set the prefix and a method to set the serial number // there is also a method to obtain the string var prefix = ''; var seq = 0; return {setPrefix: function (pre) {this. prefix = pre;}, setSeq: function (seq) {this. seq = seq;}, gensym: function () {return this. prefix + this. seq ;};}; var seqer = serial_maker (); seqer. setPrefix ("QAZ "); Seqer. setSeq (10011); console. log (seqer. gensym (); Copying code cascade (method chain) There are some methods that do not return values. If we let these methods return this instead of undefined, we can enable cascade. In a cascade operation, you can call multiple methods of the same object in one statement. Here is an example of an Ajax class library. // Use getElement ('myboxdiv ') for cascading calls of an Ajax class library '). move (100,200 ). width (100 ). height (200) l; cascade technology can produce expressive interfaces. // I think cascading is useful in some scenarios, but it should not be abused. Memory functions can record the results of previous operations in an object to avoid repeated operations that do not matter. Such optimization is called memory. It is very convenient to optimize JavaScript objects and arrays. For example, we can use recursive functions to calculate the Fibonacci series: copy the code var fibonacci = (function fib (n) {return n <2? N: fib (n-1) + fib (n-2);}); for (var I = 0; I <= 10; + I) {console. log (maid (I) + '\ n');} copies the code, but it does a lot of unnecessary work. If we make this function have a memory function, this can significantly reduce the computing workload. Copy the code var fibonacci = function () {var memo = [0, 1]; var fib = function (n) {if (typeof memo [n]! = 'Number') {memo [n] = fib (n-1) + fib (n-2);} return memo [n] ;}; return fib ;}(); for (var I = 0; I <= 10; ++ I) {console. log (fibonacci (I) + '\ n');} the copy code function collection function does not overload the ECMAScript function. It cannot be overloaded as it is in the traditional sense. In other languages, you can write two definitions for a function. As long as the two definitions (the type and quantity of accepted parameters) are different. The ECMAScript function has no signature because its parameter roommate contains "arrays" of zero or multiple values. Without the function signature, the real overload cannot be achieved. An anonymous function that imitates block-level scopes can mimic block-level scopes. the syntax of an anonymous function that uses block-level scopes (usually called Private scopes) is as follows: (function () {// here is the block-level scope}) (); what is the strict mode? ECMAScript 5 introduces the concept of strict mode, which defines a different parsing and execution model for JavaScript. In strict mode, some uncertain behaviors in ECMAScript 3 will be processed, and some insecure operations will also throw an error. Enable strict mode in the entire script. You can add the following code on the top: "use strict"; of course, you can also enable the strict mode function doSomething () in a function () {"use strict"; // function body}

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.