Front end cultivation (third day) function

Source: Internet
Author: User

Defining functions

The keyword function is used to define a function. There are two ways to define a function

(1) Function-Definition expressions
1 var f = function (x) {

}
(2) Function declaration statement
1 function funcname ([arg1 [, arg2 [..., argn]]) {2 3}

function declaration statements usually appear at the top of the JavaScript code, or can be nested within other function bodies. When nested, however, a function declaration can only be present at the top of the nested function. That is, the function definition cannot appear in the IF statement, the while statement, and other statements in the latter.

Similarities and differences

(1) all created the same new function object

(2) The function name in the function declaration statement is a variable name, and the variable points to the function object. A function definition expression does not declare a variable, and if a function definition expression contains a name, the local scope of the function will contain a name that is bound to the function object. So the name exists in the function body and refers to the function itself, which means that the name of the function becomes a local variable inside the function. The "note" function definition expression is particularly well-suited for defining functions that will only be used once

(3) Functions in a function declaration statement are explicitly "advanced" to the top of a script or function. Therefore, they are visible throughout the script and in functions. But defining a function in a function expression is different, you want to invoke the function of this definition, you must refer to it, and before you can use a function defined by an expression, you must assign it to a variable, as stated earlier: the declaration of a variable is ahead of time, but assigning a value to a variable is not advanced, so A function that is defined in an expression cannot be called until it is defined. The following code:

1 person ();   /* The function declaration statement is explicitly advanced to the top so that */2 function person () {}3 person () can be called before the definition;              /* Call after function definition is no doubt correct */
1 P (); 2 3 var p = function () {4 5}6 7/*8 printed out: Undefined is not a function variable p has not been initialized, so the function definition expression cannot be called before the function definition 9 */
The function call (1) acts as function person (age,name) {} person (12, "star"); (2) as a method var calculator = {operator1:1, operator2:2, Add:function () {This.result = This.op      Erator1 + This.operator2; } };      Calculator.add (); The method call computes the result of the Calculator.result =>2/* Creates the property and method through the object's direct amount, and calculator as the calling context, so the This keyword refers to the object */(3) as a constructor

Note: If the constructor has no formal parameters, the syntax of the JavaScript constructor call is to allow omitting the argument list and the parentheses. Therefore, any constructor call without formal parameters can omit parentheses.

(4) indirectly invoke the "later" this keyword through their call () and the Apply method

This is a keyword, not a variable, or a property name. The syntax of JavaScript is not allowed to assign a value to this. Unlike variables, the keyword this does not have scope restrictions, and nested functions do not inherit this from the function that calls it. For this we use an example to illustrate

 var o ={      m: function ()  {              var self = this;              console.log (This === o);   (1)               f ();                           function ()  {                      console.log (This === o);   (2)                        console.log (Self == o);      (3)               }      }} /* print True in the above (1) because this refers to O. (2) outputs false, at which point this is a global object or undined. (3) Output true,self refers to the this value of the external function */ 

As you know:

(1) If the nested function is called as a method, its value points to the object that called it.

(2) If the nested function is a function call, its this value is not a global object (in non-strict mode) is undefined (strict mode).

(3) If you want to access the value of this for an external function, you need to keep the value of this in a variable, which is in the same scope as the inner function. The variable self is usually used to save this.

A function introduced as a namespace

When there is a piece of JavaScript module code, this code will be used in different JavaScript programs (usually used in a variety of Web pages for client-side JavaScript). If the code defines a variable that stores the result of an intermediate calculation. So there is a problem, when the module code in a different program, you do not know whether the variable is already built, if this variable already exists, then it will conflict with the code. The solution is to put the code inside a function and call the function. The global variable becomes a local variable within the function. Use the anonymous function to define, use the following

The variables used in the function () {//module code are local variables Console.log (12) (1)} ());    End the function definition and call it immediately or (function () {Console.log (12); (2)}) (); Here is a question has not been resolved, if there are friends know, hope can help me solve, thank you! I do not know that you notice the difference between the two anonymous functions, to the output in (1) There is no semicolon, if the semicolon is wrong, can not output, no semicolon is normal output, (2) is good! Hope to get help from your friends, thank you here!

It is common to define an anonymous function and invoke it immediately in a single expression, such as whether a bug has occurred in code detection, and if this bug occurs, returns a version of the patched function!

function Properties, method (1) Length Property

Length to nothing to say, the most important thing is to belong to the arguments property of the function, in the function body, arguments.length represents the number of arguments passed in the function, in order to simulate the function overload. Take a look at the following code

1 function person (age, name, gender, addr) {2 This.age = age; 3 THIS.name = name; 4 This.gender = gender; 5 this.addr = addr;                              6/* Get the number of incoming arguments */7 switch (arguments.length) 8 {9 Case 1:
Ten break;11 Case 2:
BREAK;13 Case 3:
BREAK;15 Case 4:
break;17}18}19 20 var p = new Person (1, ' hehe '); var p1 = new Person (1, ' hehe ', false); 22 var p2 = new Person (1, ' hehe ', false, ' Hunan '); 23 24
Supplement: Arguments's callee attribute introduced
1             var factorial = function (x) {2                 if (x <= 1) return 1;3                 return x * factorial (x-1); 4             }5             Console.lo G (factorial (5)); 6/                 * Print out 120*/

The above code is for the factorial of a number, no doubt there is no error. Now make a little change, as follows

1             var factorial = function (x) {2                 if (x <= 1) return 1;3                 return x * factorial (x-1); 4             }5             var fact2 = factorial;6             factorial = function () {7                 return 0;8             }9             console.log (Fact2 (5));

It is obvious that the FACT2 variable points to two functions, and when a call to Fact2 (5) is required, the first factorial function is executed, and when executed to return x * factorial (x-1), then the second factorial function is executed, so This prints out 0. Obviously this is not the result we want, what we need is the function of factorial that is executed next or it is itself the first, so this time the callee () method comes in handy: for invoking itself. So the above code can be modified so that

1             var factorial = function (x) {2                 if (x <= 1) return 1;3                 return x * Arguments.callee (X-1); 4             }5             var Fact2 = factorial;6             factorial = function () {7                 return 0;8             }9             console.log (Fact2 (5));

Note: Arguments also has a property that looks similar to callee caller, whereas in non-strict mode, the ECMAScript standard specification specifies that the callee attribute refers to the function that is currently executing. Caller is non-standard, but most browsers implement this property, which refers to a function that is currently executing a function. The call stack can be accessed through the caller property. Recursively calls itself by callee, because it saves the address of the current execution method without error.

(2) Prototype property

Each function contains a prototype attribute, which points to a reference to an object called the prototype object. Each function contains a different prototype object. When a function is used as a constructor, the newly created object inherits properties from the prototype object. For a prototype object, please refer to the prototype and inherit this talk

(3) Call () and apply () method

Both methods can be used to call functions indirectly, and two methods allow you to explicitly specify the value of this that is required for a call, and any function can be invoked as a method of any object, even if the function is not a method of that object. Two methods can specify the arguments that are called. The call () method uses its own argument list as the argument for the function, and the Apply () method requires that the parameter be passed in as an array. In ECMAScript5 's strict mode, the first argument of call () and apply () becomes the value of this, even if the actual argument passed in is the original value or even null or undifined. In ECMASCRIPT3 and non-strict mode, the passed null and undefined are replaced by the global object, while the other raw values are replaced by the corresponding wrapper object.

The following code is used to explain the above concept (1) Call () method
1                 function Person (age,name) {2                     this.age=age; 3                     this.name=name; 4                 } 5     6                 var obj=new Object (); 7                 Person.call (obj,12, ' little Black '); 8                 Console.log (obj.age); 9                 Console.log (obj.name);                /*12                Creates an empty object, obj, at which point the call () method of the person class is called, and obj is passed in, at which point obj becomes its calling context, and this is obj, which can eventually print 12 and small black                */
(2) Apply () method

For more usage Please refer to: Apply () details

(3) Bind () method

Bind () is a new method in ECMAScript5, but it is easy to emulate bind () in ECMASRIPT3, which is the main function of binding a function to an object, as the name implies.

1 function f (y) {2        return this.x + y; 3} 4 var o = {x:1}; 5 var g =  f.bind (o); 6 Console.log (G (2)); 7  8 F Unction bind (F,o) {9        if (f.bind) return F.bind (O), ten        else return function () {One               return f.apply (o, arguments) ;        };13}

The above binds the function f to the object o, and when invoking the bind () method on the function f () and passing in an object o as a parameter, this method returns a new function. Calling the new function will invoke the original function f () as an O method. Any arguments passed into the new function are passed into the original function. In the above F.bind (o), then the function f () in this is O, at this time this.x=1, after binding return the new function g, and then call the function g (2), when the function f () is its argument, so print out 3.

function arguments (1) Pass the original type (so-called value types in C #)
1                          function person (age) {2                              age++;3                          }4                          var = 12;5 person                          (age), 6                          console.log (age);

How much do you think it will be printed according to the above code? An analysis of our sentence:

(1) var age = 12; a space address on the stack is assumed to be 0x1, at which time the value of 0x1 is the variable age and its values are 12. (2) person (age), call the function person and pass in the argument, at this time the formal parameter in person is equivalent to a local variable, so also on the stack to open a space address is 0x2, the variable is age, the above (1) is assigned to (2) the value of age so the same 12, Then into the function body, the age++, adding the value of the newly created local variable, does not change the age value in (1). (3) Print out 12. (2) Transitive objects (reference types in the so-called C #)
1                          function Person (p) {2                                 p.age++;3                          }4                          var p = {Age:12};5 person                          (p); 6                          Console.log (p.age);

Analysis in the same vein

(1) var p = {Age:12}; First open a space on the stack address to a value of 0x1 is null, and then on the right side on the heap first open a space address of 0x2 empty object, and then define the attribute age and its value is 12, and this object points to the variable p, so the value of the variable is 0x2. (2) person (p); the same p at this time is equivalent to the person class of local variables, first on the stack open a space address is OX3 name p of the variable, at this point (1) The value of P in the 0x2 assigned to the value of P in 0x3, so at this time the value of 0x3 is 0x2, That is when ox2 points to the heap on the object with the address of 0x2, which has an age value of 12. It then goes inside the function body, age++ its age, and the property of the object on the heap becomes 13. (3), the age of the printed p is 13. Summary arguments whether to pass the original type (value type) or object (reference type) only need to see the value of the variable on the stack is the value of the stored or the address, if a value is stored, it is equivalent to copying one copy, which does not change the original value, and if the value of the variable is the address, the value in the original object will be affected if the value is changed in the function body.

A book is a medicine, and a good reader can cure a fool.

Front end cultivation (third day) function

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.