Javascript learning notes (7) Functions

Source: Internet
Author: User

1. function internal attribute arguments
Arguments is used to save the function parameters. arguments. callee points to a function with an arguments object.


1 // factorial
2 function factorial (num ){
3 if (num <= 1 ){
4 return 1;
5} else {
6 return num * arguments. callee (num-1); // use agreements. callee instead
7}
8}
9
10 var trueFactorial = factorial;
11 factorial = function {
12 return 0;
13}
14 alert (trueFactorial (5); // 20
15 alert (factorial (5); // 0
2. Function Attributes and Methods
Length attribute, indicating the number of function parameters

3. apply () and call () Methods
The apply () and call () methods are used to pass parameters or expand the function scope.


1 // PASS Parameters
2 function sum (num1, num2 ){
3 return num1 + num2;
4}
5 function callSum (num1, num2 ){
6 return sum. call (this, num1, num2); // The first parameter this, which is listed later
7}
8 alert (callSum (10, 10); // 20
9
10 function calSum1 (num1, num2 ){
11 return sum. apply (this, arguments); // The first parameter this, the second parameter arguments
12}
13 function calSum2 (num1, num2 ){
14 return sum. apply (this, [num1, num2]); // The first parameter this, and the second parameter is the parameter Array
15}
16 alert (callSum1 (10, 10); // 20
17 alert (callSum2 (10, 10); // 20

1 // change function Scope
2 window. color = "red ";
3 var o = {color: "blue "};
4 function sayColor (){
5 alert (this. color );
6}
7 sayColor (); // red
8 sayColor. call (this); // red
9 sayColor. call (window); // red
10 sayColor. call (o); // blue

 

 

From Sunday walk

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.