The scope problem of functions and functions, arguments

Source: Internet
Author: User

This value : When the function executes, the This keyword does not point to the running function itself, but instead points to the object that called the function. So if you want to get a reference to the function itself inside the function, you can use only the function name or use the Argument.callee property ( Not available in Strict mode ), if the function is an anonymous function, you can only use the latter.

1. Defining functions

Three different ways:

1) Functions Declaration (Function Statement)

name ([paramparamparamstatements }
Name of the function name.

The name of the parameter of the Param function, a function can have up to 255 parameters.

Statements these statements form the function body of the function.

2) Functional expressions (function operators)

function expressions and function declarations are very similar, and they even have the same syntax (see function operators for details):

function [name] ([paramparamparamstatements }
Name function name, can be omitted, omit the function name, the function becomes an anonymous function.

The name of the parameter of the Param function, a function can have up to 255 parameters.

Statements these statements form the function body of the function.

3) Function constructor

Like other types of objects, a function object can also be created using the new operator:

New Function (arg1arg2argNfunctionbody)
Arg1, arg2, ... arg NOne or more variable names to be the parameter names of the function. The type is a string, and the value must be a valid JavaScript identifier, such as function ("X", "Y", "Alert (x+y)"), or multiple identifiers for a comma connection, such as function ("X", Y "," Alert (x+y) ")

Functionbody A string that contains one or more statements that comprise the function body of the function.

Even if the function function is called directly without using the new operator, the effect is the same, and you can still create one.

Note:The function constructor is not recommended for creating functions. Because in this case, the body of the function must be specified by a string. This will prevent some JS engine to do program optimization, but also cause some other problems.2.arguments objects

Inside the function, you can use the arguments object to get all the incoming arguments to the function. View arguments.


The arguments object is a local variable inside the function; arguments is no longer a function's property.

You can get all the parameters of a function inside the function by using the arguments object. This object establishes an entry for each parameter passed to the function, and the index number of the entry starts at 0. For example, if a function has three parameters, you can get the parameters in the following ways:

Arguments[0] arguments[1] arguments[2 ]

Parameters can also be re-assigned:

ARGUMENTS[1] = ' new value ';

The arguments object is not a true array. It is similar to an array, but has no properties and methods specific to the array, except for length. For example, it does not have a pop method. However, you can convert it to an array:

var = Array. Prototype. Slice. Call(arguments) ;
Note: The slice method should not be used on arguments objects, which hinders the optimization of the JavaScript engine (such as the V8 engine). Instead, a new array should be constructed by traversing the arguments object.


The arguments object is only valid inside the function, and an error occurs when calling the arguments object outside the function.

If you call a function, you can use the arguments object when the number of arguments for the function is more than the number of arguments it explicitly declares. This technique is useful for functions that have a variable number of parameters. You can use Arguments.length to get the number of arguments, and then you can use Argumentsobject to manipulate each parameter. (To get the number of arguments to the function when a function is defined, use the Function.length property.) )

function Myconcat (separator) {  var args = Array.prototype.slice.call (arguments, 1);  return Args.join (separator);}



Returns "Red, orange, Blue" Myconcat (",", "Red", "orange", "Blue");//returns "elephant; Giraffe; Lion Cheetah "Myconcat ("; "," Elephant "," giraffe "," lion "," cheetah ");



3. Recursion

A function can point to and call itself. There are three ways to make a function point to itself:

    1. Name of function
    2. Arguments.callee
    3. An in-scope variable that points to a function

For example, consider the following function definition:

var foo = function bar () {   //statements go here};

In the body of a function, the following statements are equivalent:

    1. Bar ()
    2. Arguments.callee ()
    3. Foo ()
A function called itself is called a recursive function. In some ways, recursion is analogous to a loop. Executes the same piece of code multiple times and requires a condition (to avoid endless loops, or endless recursion). For example, the following loop:
function Walktree (node) {   if (node = = null)//       return;   Do something with node for   (var i = 0; i < node.childNodes.length; i++) {      walktree (node.childnodes[i]);   }}
It is possible to convert each recursive algorithm to non-recursive, but usually the logic becomes very complex, and this requires a stack. In fact, the recursion itself uses the stack: the function stack. (Every time I feel confused in this stack)
function foo (i) {   if (I < 0)      return;   Document.writeln (' Begin: ' + i);   Foo (i-1);   Document.writeln (' End: ' + i);} Foo (3);
Begin:3begin:2begin:1begin:0end:0end:1end:2end:3
4. Nesting functions and closures

You can nest a function inside another function. A nested function (an intrinsic function) is a private function that is only a function (an external function) that is nested within it. This creates a closure.

function Addsquares (A, b) {   function Square (x) {      return x * x;   }   Return Square (a) + square (b);} A = Addsquares (2,3); Returns 13b = Addsquares (3,4); Returns 25c = Addsquares (4,5); Returns 41
Since the inner function forms a closure, you can return the intrinsic function as a return value, which refers to the two parameters of the external function and the intrinsic function:
function outside (x) {   function inside (y) {      return x + y;   }   return inside;} Fn_inside = Outside (3); result = Fn_inside (5); Returns 8RESULT1 = Outside (3) (5); Returns 8
5. Local variables within a function

Arguments: An "array of Classes" object that contains all the arguments passed into the current function.

Arguments.callee : points to the function that is currently executing.

Arguments.caller : Point to the function that invokes the currently executing function, use Arguments.callee.caller instead of

Arguments.length: The number of arguments passed in to the current function.

arguments.callee.length:Number of formal parameters

Example: detecting whether a function exists

You can use the TypeOf operator to detect whether a function exists. In the following example, the Nofunc property of the Window object is first detected as a function, and if it is, it is called, otherwise, some other action is performed.

if (' function ' = = typeof Window.nofunc) {   //Call Nofunc ()} else {   //Other actions}

Note that in the IF statement, a reference to the Nofunc function is used, with only the function name and no subsequent parentheses "()", so that the function is not called.




The scope problem of functions and functions, arguments

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.