Detailed JavaScript function _javascript tips

Source: Internet
Author: User
Tags closure

A function is a set of statements that can be run anywhere, and functions are important as the core of a ECMAScript. A function is an event-driven or reusable block of code that executes when it is invoked. That is, a function is a section of JavaScript code that is defined once but can be invoked or executed any number of times. A function can sometimes have arguments, that is, a local variable that specifies a value when the function is invoked. Functions often use these parameters to compute a return value, which also becomes the value of the function invocation expression.
function Declaration
A function is a core concept for any language. Functions allow you to encapsulate any number of statements, and you can call execution anywhere, anytime. The functions in JS are declared with the function keyword, followed by a set of parameters and the function body.
The basic syntax for a function is this:

<span style= "FONT-SIZE:18PX;" >function functionname (arg0, arg1, ... argn) { 
 statements 

There are three types of function declarations defined by ECMAScript:
(1) normal function declaration

<span style= "FONT-SIZE:18PX;" >function Box (num1,num2) {return 
 num1+num2; 
} </span>

(2) Use variables to initialize the function of what to declare

<span style= "FONT-SIZE:18PX;" >var box=function (num1,num2) {return 
 num1+num2; 

(3) Using function constructor declarations

Copy Code code as follows:
<span style= "FONT-SIZE:18PX;" >vax box=new Function (' num1 ', ' num2 ', ' num1+num2 ');</span>

The type of function and the Call of function
The ECMAScript Grammar stipulates
(1) functions with no parameters:The declaration of a function has no parameters and can be used directly when calling a function.

function box () { 
 document.write ("I am Chinese!") "); 
} 
box ();//Function call 

The result of the run is: I'm Chinese!
(2) functions with parameters: when the declaration of a function defines the parameter variable, the argument can be multiple.

function box (name,age) { 
 document.write ("Your name is:" +name+ "Your Age is:" +age); 
} 
Box ("John", "24");//Function call 

The result of the run is: Your name is: John
Your age is: 24
(3) a function with a return value
Functions with parameters and parameters that do not have a return value defined, but are executed directly after the call, in fact, any function can implement the return value by returning statement followed by the value to be returned
1), function without parameters

function box () {return 
 "I'm Chinese!" "; 
} 
document.write (Box ()); 

With the above output result: I am a Chinese!
2), function with parameters

function box (name,age) {return 
 "Your name is:" +name+ "<br/>" + "Your Age is:" +age; 
} 
document.write (Box ("John", "24"));//Function call 
document.write (" 
 

The results of the run are:

(4) function as a value (more special)
First, let's look at a function as an example of a regular variable:

function box (sum,num) { 
 return sum+num;//this is where the returned value of functions is passed as normal variables 
} function 
sum (num) {returns 
 num+ ; 
} 
var result=box (sum); 
document.write ("result=" +result); 

The output of the page is: result=30
The following is a function that is carefully distinguished from the above:

function box (sum,num) {return 
 sum (num);//This is passed here is the functional 
} function 
sum (num) {return 
 num+10; 
} 
var result=box (sum,10); 
document.write ("result=" +result); 

The output of the page is: result=20
internal properties of functions
Inside the function, there are two special objects: the arguments object and the This object. The arguments object is a class array object that contains all the arguments in the incoming function, the main purpose is to save the function arguments, the main attribute has length, and this property is the number of parameters of the dynamic judgment function. But this object also has a property called Callee, which is a pointer to the function that owns the arguments object.
(1) The length property of the arguments object
js function does not mind passing in the number of parameters, nor because the parameters are not uniform and error. In fact, a function body can be used to arguments objects
Receives the passed in parameter.
Let's take a look at one of the problems we've encountered with function pass arguments: The function declaration does not know how many arguments to define, but there is more in the call function
Problems that are out of or insufficient.

function box () {return 
 arguments[0]+ "|" +ARGUMENTS[1]; 
} 

The result of the output is: 1|2. So the output is clearly inconsistent with what we want to do, so how to solve it?
With the length property of the arguments object, we can get the number of parameters to avoid the error appearing above.

function box () {return 
 arguments.length; 
} 
document.write (Box (1,2,3,4,5,6)); 

Output: 6
We can also use the length property to intelligently determine how many parameters, and then the parameters of a reasonable application, for example, to implement an addition operation, all the numbers passed in, and the number of numbers is uncertain.

function box () { 
 var sum=0; 
 if (arguments.length==0) 
 {return 
 sum; 
 } 
 for (Var i=0;i<arguments.length;i++) 
 { 
 sum=sum+arguments[i]; 
 } 
 Return sum;//returns the cumulative result 
} 
document.write (Box (1,2,3,4,5,6)); 

Output: 21
(2) The callee property of the arguments object
or the problem: we are familiar with the problem of recursion, JS is no exception

function box (num) { 
 if (num<=1) 
 {return 
 1; 
 } 
 else 
 {return 
 num*box (num-1);//Recursive 
 } 
} 
document.write (Box (4)); 

Output: 24
For the factorial function is generally used to the recursive algorithm, so the function must swap itself, if the function name does not change is not a problem, but once the function name changes, internal calls need to be modified. To solve this problem, you can use Arguments.callee instead.

function box (num) { 
 if (num<=1) 
 {return 
 1; 
 } 
 else 
 {return 
 Num*arguments.callee (num-1)//Recursive 
 } 
document.write (Box (4)); 

Output: 24
(3) This object
This is similar to this in Java and C # in the case of another special object inside the function, in other words, this refers to the object to which the function is operated, or to the scope where the function call statement is. When a function is called in a global scope, this object refers to the window (window is an object, the largest object in JavaScript, and the outermost object).

var color= "red";//The color here is a global variable, and this variable is the property of window 
document.write (window.color+ "<br/>"); 
document.write (this.color+ "<br/>"); 
var box={ 
 color: "Blue",//The color here is the property under box, is a local variable 
 saycolor:function () {return 
 this.color;// This is only the color in box} 
; 
document.write (Box.saycolor () + "<br/>");//local 
document.write (this.color)/Global 

The results of the run are:

Iv. function Properties and methods
(1) Functions in JavaScript are objects, so functions also have properties and methods. Each function contains two attributes: Length and prototype. Where the Length property represents the number of named arguments that the function expects to accept.

function box (num1,num2) {return 
 num1+num2 
} 
document.write (box.length); 

The result of the output; 2
For the prototype property, it is the true location, the prototype, that holds all instance methods. This property we do not introduce too much first. There are two methods under the prototype property: Apply () and call (), and each function contains the two methods that are not inherited. The purpose of both methods is to call a function in a particular scope, which is actually equal to setting the value of this object in the function body.

function box (num1,num2) {return 
 num1+num2 
} 
function Saybox (num1,num2) {return 
 box.apply (this,[num1,num2]);//this represents the scope, this is window,[] the parameters required to represent box 
} 
function SayBox2 (num1,num2) {return 
 box.apply (this,arguments);//arguments object represents parameters required for box 
} 
document.write (Saybox (10,10) + "<br/>"); 
document.write (SayBox2 (10,10)); 

The result of the output is: 20
20
(2) The call () method and the Apply () method extend
The call () method is the same as the Apply () method, and they differ only in the way they receive the parameters. For the call () method, the first argument scope, unchanged, only changes the rest of the parameters are passed directly to the function.

function box (num1,num2) {return 
 num1+num2 
} 
function Callbox (num1,num2) {return 
 box.call (this,num1,num2);//Difference Apply () method 
} 
document.write ( 10,10)); 

The result of the output is: 20
The call () method and the Apply () method really work on the scope that the extension function relies on to run

var color= "red";//global variable 
var box={ 
 color: "Blue",//local variable 
}; 
function Saycolor () {return 
 this.color; 
} 
document.write (Saycolor () + "<br/>");/scope in Window 
document.write (Saycolor.call (this) + "<br/>"); Scope under Window 
document.write (saycolor.call (window) + "<br/>");//scope under Window 
document.write ( Saycolor.call (box));/scope under box, objects posing as 

The results of the output are:

The biggest benefit of extending a scope using the call () method or the Apply () method is that the object does not need to have any coupling with the method. In other words, the box object and the Saycolor () method will not have redundant associated operations, such as; Box.saycolor=saycolor;
Five, ECMAScript closure
One of the most misleading ecmascrip is that it supports closures. Closure refers to the lexical representation of functions that include variables that are not evaluated, that is, functions can use variables defined outside the function.
In fact, I've already used the closure in the previous post, such as easy learning JavaScript seven: JavaScript in the Process Control statements used in the variable time is a global variable, the function MyFunction () Use this global variable, not defined by the function itself. Let's take a look at that example:

var time=new Date (). getHours (); 
document.write ("Current Beijing Time:" +time); 
function MyFunction () 
{ 
 var x= ""; 
 if (time<20) 
 { 
 x= "Good Day"; 
 } 
 document.getElementById ("Demo"). Innerhtml=x 
} 

(1) Simple closure example
using global variables in ECMAScript is a simple closure instance. Consider what the output of the following code is:

var smessage = "Hello World"; 
function SayHelloWorld () { 
 document.write (smessage); 
} 
SayHelloWorld (); 

In the above code, the script is loaded into memory and does not compute the value of the variable smessage for the function SayHelloWorld (). The value of the smessage is only for later use, that is, the interpreter knows the value of the smessage to be checked when the function is called. Smessage will be assigned in the (last line) of the function call SayHelloWorld, displaying the message "Hello World".
(2) a complex closure instance
Defining another in one function makes the closure more complex. For example:

var ibasenum = 10;//global variable 
function addnum (INUM1, iNum2) { 
 function Doadd () {return 
 iNum1 + iNum2 + ibasenum;
   } return 
 doadd (); 
} 
document.write (Addnum (10,10)); 

Here, the function Addnum () includes the function Doadd () (closure). An intrinsic function is a closure because it gets the value of the parameter INum1 and iNum2 of the external function and the global variable Ibasenum. The last step of Addnum () calls Doadd (), adds two parameters and global variables, and returns their sum. The important concept to grasp here is that the Doadd () function does not accept parameters at all, and the values used are obtained from the execution environment, so the result of the output is: 30.
As you can see, closures are a very powerful part of ECMAScript that can be used to perform complex computations. As with any advanced function, be careful with closures, as they can become very complex.

The above is the entire content of this article, I hope to help you learn.

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.