Study Notes of JavaScript language-Chapter 4 Functions

Source: Internet
Author: User

Chapter 4 Functions

4.1 In JavaScript, a function is an object.
4.2. Function objects are connected to function. Prototype (the prototype object itself is connected to object. Prototype ).
4.3 When a function is created, two additional hidden attributes are attached: The function context and the code that implements the function behavior.
4.4. The difference between a function and other objects is that it can be called.
4.5. Function objects can be created using the function literal:

// Create a variable named add and assign values to the functions of two digital cameras. VaR add = function (a, B) {return a + B ;};

The function literal contains four parts.
The first part is the reserved word function.
The second part is the function name, which can be omitted-"anonymous function ". The function name can be used to call itself recursively.
The third part is a set of parameters enclosed in parentheses. Each parameter is separated by a comma.
The fourth part is a set of statements enclosed in curly braces. These statements are the body of the function. They are executed when the function is called.
4.6. The function literal can appear where any expression is allowed, and the function can be defined in other functions. An internal function can naturally access its own parameters and variables, and it can also easily access the parameters and variables of the function nested in it. A function object created using the function literal contains a connection to the external context. This is called"Closure". It is the foundation of JavaScript's powerful expressiveness.
4.7 calling a function will suspend the execution of the current function and pass the control right and parameters to the new function.
4.8 apart from the declared parameters, each function also receives two additional parameters: This and arguments.
4.9 The value of this parameter depends on the call mode.There are four call modes in javascript: method call mode, function call mode, constructor call mode, and apply call mode..
4.10 when the actual number of parameters and the number of formal parameters do not match, it will not cause a runtime error. If the actual parameter value is too large, the excess parameter value will be ignored. If the actual parameter value is too small, the missing value will be replaced with undefined.
4.11. No type check is performed on the parameter values. Any type value can be passed to the parameter.
4.12 method call mode: When a function is saved as an attribute of an object, it is called a "method ". When a method is called, this is bound to this object.

// Create a myobject. It has a value attribute and an increment method. // The increment method accepts an optional parameter. If the parameter is not a number, 1 is used by default. VaR myobject = {value: 0, increment: function (INC) {This. Value + = typeof Inc = 'number '? INC: 1 ;}}; myobject. increment (); document. writeln (myobject. value); // 1myobject. increment (2); document. writeln (myobject. value); // 3

Demo
4.13 function call mode: When a function is not an object attribute, it is called as a function:

VaR sum = add (3, 4); // The sum value is 7.

When a function is called in this mode, this is bound to a global object. This is a language design error. If it is correct, this should be bound to the this variable of the external function. The consequence of this design error is that the method cannot use the internal function to help it work. Because the internal function is bound with an incorrect value, the method's access to the object cannot be shared. Solution: This method defines a variable and assigns it a value of this.
4.14 constructor call mode: If a function is called with new in front of it, a new object hidden from the prototype members connected to the function will be created, at the same time, this will be bound to the new object.

// Create a constructor function named quo. It constructs an object with the status attribute. VaR quo = function (string) {This. Status = string ;}; // provides a public method named get_status for all quo instances. Quo. prototype. get_status = function () {return this. status ;}; // construct a quo instance var myquo = new quo ("confused"); document. writeln (myquo. get_status (); // confusing

Demo
Note: This writing method is not recommended by the author. The reasons are described in the following chapter.
4.15 apply call mode: Because Javascript is a functional object-oriented programming language, functions can have methods.
The apply method can construct a parameter array and use the courage to call the function. It also allows us to select the value of this.
The apply method receives two parameters. The first one is the value that will be bound to this. The second is the parameter array.

// Construct an array containing two numbers and add them together. VaR array = [3, 4]; var sum = Add. Apply (null, array); // The sum value is 7 // construct an object containing status members. VaR statusobject = {status: 'A-OK '}; // statusobject does not inherit from quo. prototype, but we can call the get_status Method on statusobject, although statusobject does not have a method named get_status. VaR status = Quo. Prototype. get_status.apply (statusobject); // The status value is 'a-OK '.

Demo
4.16. The function can use the arguments array to access all the parameter lists that are passed to it when it is called. Due to a design error in the language, arguments is not a real array, but an object similar to an array. Arguments has a Length attribute, but it lacks all array methods.
4.17 a function always has a return value. If no value is specified, undefined is returned.
4.18 If the function is called with a new prefix and the returned value is not an object, this (the new object) is returned ).
4.19 throw statements interrupt function execution. It throws an exception object that contains the name attribute that can identify the exception type and a descriptive message attribute. You can also add other attributes.
4.20 recursive functions call their own functions directly or indirectly. Typical recursive function example-Tower of death (more visible wiki: http://zh.wikipedia.org/wiki/%E6%B1%89%E8%AF%BA%E5%A1%94 ).

var hanoi = function (disc, src, aux, dst) {if (disc > 0) {hanoi(disc - 1, src, dst, aux);document.writeln('Move disc ' + disc + ' from ' + src + ' to ' + dst);hanoi(disc ? 1, aux, src, dst);}};hanoi(3, 'Src', 'Aux', 'Dst');

When the number of disks is 3, this solution is returned.
Move disc 1 from SRC to DST
Move disc 2 from SRC to aux
Move disc 1 from DST to aux
Move disc 3 from SRC to DST
Move disc 1 from aux to SRC
Move disc 2 from aux to DST
Move disc 1 from SRC to DST
Demo
4.21 tail recursion is a special form of recursion in which the function executes the recursive call statement at the end of the function.
4.22. tail recursion can be replaced with a loop, but JavaScript does not optimize tail recursion.
4.23. Scope controls the visibility and lifecycle of variables and parameters. Purpose: 1. Reduce variable name conflicts; 2. provide automatic memory management.
4.24. JavaScript does not support block-level scopes of code blocks.
4.25. Javascript has function scopes. Parameters and variables defined in the function are invisible outside the function. variables defined in any position in the function are visible anywhere in the function.
4.26 because JavaScript lacks block-level scopes, it is recommended to declare all variables that may be used in the function at the top of the function body.
4.27. The benefit of scope is that internal functions can access parameters and variables (except this and arguments) that define their external functions ).
4.28 closure Example 1: an interesting situation is that internal functions have a longer life cycle than external functions.

VaR myobject = function () {VaR value = 0; // Private variable, visible to increment and getvalue return {increment: function (INC) {value + = typeof Inc === 'number '? INC: 1 ;}, getvalue: function () {return value ;}}(); document. writeln (myobject. value); // undefineddocument. writeln (myobject. getvalue (); // 0myobject. increment (2); document. writeln (myobject. getvalue (); // 2myobject. increment (4); document. writeln (myobject. getvalue (); // 6

Demo
Taking a closer look, a function is not assigned to myobject. Instead, assign a value to the result returned by the callback function. This function returns an object that contains two methods, and these methods continue to enjoy the privilege to access the value variable.
4.29. Closure Example 2: Create a constructor named quo

// It constructs an object var quo = function (Status) {return {get_status: function () {return status ;}}; with the get_status method and status private attribute ;}};}; vaR myquo = quo ("amazed"); document. writeln (myquo. get_status (); // amazed

Demo
This quo function is designed to be used without adding new to the front, so the first letter of the name is not capitalized. When we call quo, it returns a new object containing the get_status method. A reference of this object is stored in myquo. Even if quo has been returned, the get_status method still has the permission to access the status attribute of the quo object. The get_status method does not access a copy of this parameter; It accesses the parameter itself. This is possible because the function can access the context when it is created. This is calledClosure.
4.30. Closure Example 3: a more useful example

// Define a function that sets a DOM node's color// to yellow and then fades it to white.var fade = function (node) {var level = 1;var step = function () {var hex = level.toString(16);node.style.backgroundColor = '#FFFF' + hex + hex;if (level < 15) {level += 1;setTimeout(step, 100);}};setTimeout(step, 100);};fade(document.body);

Demo
If settimout exists, the level variable in the fade function will be assigned a value again. The Fade function has returned the value before, but as long as the fade internal function needs it, its variables will be retained.
4.31 internal functions do not need to be copied when accessing external functions.
4.32. A "module" is a function or object that provides interfaces but hides the state and implementation. You can use functions and closures to construct modules.
4.33. The module mode uses function scopes and closures to create associations between bound objects and private members.
4.34 The general form of the module mode is: return this privileged function at last, or save them to a accessible place.
4.35 using the module mode can discard the use of global variables. It promotes information hiding and other excellent design practices. The module mode is very effective for application encapsulation or other Singleton objects.
4.36 generate a secure object serial_maker using the single-instance feature of module mode.

VaR serial_maker = function () {// returns an object used to generate a unique string // the unique string consists of two parts: prefix + Serial Number // This object contains a method to set the prefix, one method to set the serial number and one gensym method to generate a unique string var prefix = ''; var seq = 0; return {set_prefix: function (P) {prefix = string (p) ;}, set_seq: function (s) {seq = s ;}, gensym: function () {var result = prefix + seq; SEQ + = 1; return result ;}};}; var seqer = serial_maker (); seqer. set_prefix ('q'); seqer. set_seq (1000); var unique = seqer. gensym (); // unique is "q1000" document. writeln (unique); document. writeln (seqer. gensym (); document. writeln (seqer. gensym (); document. writeln (seqer. gensym ());

Demo
4.37 enable cascade if you want to return this instead of undefined for some methods without return values.

Summary:
This chapter is the most abstract and hard to understand."Closure". In my understanding, "closure" is a function (assuming the function name is fa). The function Fa has a subfunction (assuming the function name is FB ), the sub-function FB can read the private variables of its external parent function FA, which enables communication between the internal function FB and the external function FA, but all of this is effective within the fa, when FA communication is interrupted, it is closed because it cannot be connected with the outside. Therefore, it can be called "closure". When it is translated into Chinese, it becomes a "closure ", the package can be understood as independent of "closed.
This article easily explains what a closure is --Learning JavaScript closures.

Refer:
English Reference documents:Javascript: the good parts
Websites that provide learning help:
1. 10 design defects of JavaScript
2. Learning JavaScript closures

3. Tower of Hanoi demonstration

Reprinted please indicate the source: http://blog.csdn.net/xxd851116/article/details/7669803

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.