Easy Learning JavaScript eight: JavaScript functions

Source: Internet
Author: User

Functions are a set of statements that can be run anywhere, and functions as the core of ECMAScript are important. The function is event-driven or when it is

A reusable block of code that is executed when it is called. That is, a function is a piece of JavaScript code that is defined once but can be called or executed any number of times. Letter

A number sometimes has parameters, that is, a local variable that specifies a value when the function is invoked. Functions often use these parameters to calculate a return value, which is also a function of the

The value of the number call expression.

a function declaration

Functions are a core concept for any language. Functions can encapsulate any number of statements, and can be anywhere, at any time

Called execution. The functions in JS are declared using the function keyword followed by a set of parameters and the body of the function.

The basic syntax for a function is this:

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

There are three ways to declare a function ECMAScript:

(1) General function declaration

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

(2) Using variables to initialize the function of what is declared

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

(3) Using function constructor declaration

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

The type of two functions and the invocation of functions

The ECMAScript Grammar prescribes

(1) A function without parameters: When the function is declared, there are no arguments, and the function is invoked directly when it is called.

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

The result of the operation is: I am Chinese!

(2) A function with parameters: the declaration of a function defines a parameter variable at the same time, and the parameter can be multiple.

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

The result of the operation is: Your name is: Zhang San

Your age is: 24

(3) function with return value

A function with parameters and no parameters, which does not define a return value, but executes directly after the call, in fact, any function can pass the return statement

followed by the value to return to implement the return value

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

With the above output: I am Chinese!

2 Functions with parameters

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

The result of the operation is:


(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;//is passed here is the return value of the functions as normal variables}function sum (num) {        return num+10;} var result=box (sum),;d ocument.write ("result=" +result);

The output of the page is: result=30

The following pass is a function, carefully and above the distinction:

function box (sum,num) {        return sum (num), or//This is passed}function sum (num) {        return num+10;} var result=box (sum,10);d ocument.write ("result=" +result);

The output of the page is: result=20

Internal properties of three 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 the passed in function

All parameters, the main purpose is to save the function parameters, the main property has length, this property is a dynamic judgment function how many parameters. But that's right.

Like there is also a property called Callee, which is a pointer to the function that owns the arguments object.

(1) Length property of the arguments object

The JS function does not mind passing in the number of parameters, nor because the parameters are not uniform and error. In fact, the function body can be arguments objects to

Receives the passed in parameters.

Let's take a look at one of the problems we encountered in the function pass parameter: The function declaration does not know how many parameters to define, and the call function has many

Out of the problem or insufficient.

function box () {       return arguments[0]+ "|" +ARGUMENTS[1];} document.write (Box (1,2,3,4,5,6));

The result of the output is: 1|2. So the output is obviously 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 and avoid the error 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 apply the parameters reasonably, for example, to implement an addition operation,

Accumulate all incoming numbers, and the number 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) Callee property of arguments object

Still 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 generally use recursive algorithm, so the function inside must be swapped with itself, if the function name does not change is no problem, but once changed

variable function name, internal calls need to be modified one by one. In order 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

Another special object inside the function is this, which behaves roughly like this in Java and C #, in other words, this refers to a function to execute

The action object, or the scope where the function call statement is located. When a function is called in the global scope, the 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/>");d Ocument.write ( this.color+ "<br/>") var box={    color: "Blue",//The color here is the property under box, is the local variable    saycolor:function () {         return this.color;//This can only be in box color    }};d Ocument.write (Box.saycolor () + "<br/>");//local document.write ( This.color);//Global

The result of the operation is:


Four function properties and methods

(1) Functions in JavaScript are objects, so functions also have properties and methods. Each function consists of two properties: length and prototype. Its

, 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 real place where all instance methods are saved, that is, prototypes. We do not introduce too much of this property first.

There are two methods under the prototype attribute: Apply () and call (), each containing the two non-inherited methods. Both of these methods are used in specific

The function that is called in the scope of the function is actually equal to the value of the this object in the body.

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

The result of the output is: 20

20

(2) Call () method and apply () method extension

The call () method is the same as the Apply () method, and they differ only in the way that they receive parameters. For the call () method, the first parameter is the function

Domain, there is no change, only 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);//Differentiate Apply () method}document.write (Callbox (10,10));

The result of the output is: 20

The call () method and the Apply () method really function as the scope on which the extension function is run

var color= "red";//global variable var box={   color: "Blue",//local variable};function saycolor () {   return this.color;} document.write (Saycolor () + "<br/>");//Scope in Windowdocument.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, the object is impersonating
The result of the output is:


The biggest benefit of using the call () method or the Apply () method to extend the scope is that the object does not need to have any coupling with the method. Other words

There is no extraneous operation between the box object and the Saycolor () method, for example; box.saycolor=saycolor;

Five ECMAScript closure Package

One of the most misleading ecmascrip is that it supports closures. Closure refers to the function of the lexical representation of variables that are not evaluated, that is,

That a function can use a variable defined outside of a function.

In fact, I have used closures in the previous blog post, such as the easy learning of JavaScript seven: variables used in Process Control statements for JavaScript

Time is a global variable, and the function MyFunction () uses this global variable, which is 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

The use of global variables in ECMAScript is a simple closure instance. Consider what the result of this code output is:

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

In the above code, after the script is loaded into memory, the value of the variable smessage is not computed for the function SayHelloWorld (). This function catches

The value of smessage is only for later use, that is, the interpreter knows to check the value of smessage when calling the function. Smessage will

The function call SayHelloWorld () is assigned in the (last row) and displays the message "Hello World".

(2) Complex closure cases

Defining another in one function makes closures 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 parameters of the external function iNum1 and

The value of the INUM2 and global variable ibasenum. The last step of Addnum () calls Doadd (), adds two parameters to the global variable, and returns it

Their and. The important concept to master here is that the Doadd () function does not accept parameters at all, and the values it uses are obtained from the execution environment, so the output

Knot the fruit is: 30.

As you can see, closures are a very powerful and versatile part of ECMAScript that can be used to perform complex computations. Just like with any advanced function

, use closures with caution, as they can become very complex.

If you want to learn more about the JS function, refer to the ECMAScript function.

Easy Learning JavaScript eight: JavaScript functions

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.