JS function Learning

Source: Internet
Author: User

1 function declarations and function expressions

A function declaration defines a function by naming it, and a function expression is an anonymous way of defining a function (a function is an object that executes code in a particular environment)

function A () {
Console.log (' a ');
}
A (); function declaration

var a = function () {
Console.log (' a ');
};
A ();//function expression

The difference between the two is that the way the function is declared can be promoted, which means that the function is called before the function's declaration statement

A ();
function A () {
Console.log (' a ');
}//This won't be an error.

function expressions cannot be

A ();
var a = function () {
Console.log (' a ');
}; will be error a not defined

2 Arguments objects

function Test () {
Console.log (arguments[0],arguments[1],arguments[2],arguments.length);
}

Test (+/-); 1 2 3 3

Use the arguments object to get the corresponding arguments

There's another way to use it.

function factorial (n) {
if (n <= 1) {
return 1;
} else {
Return N*arguments.callee (n-1);
}
}
Console.log (factorial (5));

Get a reference to the function object being executed by Arguments.callee (very good usage)

3 scopes

var a = 100;

function Test () {
Console.log (a);

var a = 20;
Console.log (a);
}
Test ();//undefined 20

I started to think that the first a would access global variables outside of the function, not really, because the scope of Var a declared inside the function was the entire function and it was not assigned when it was first accessed.

The code above is equivalent to

var a = 100;

function Test () {
var A;
Console.log (a);

var a = 20;
Console.log (a);
}
Test ();

There is no block-level scope in JavaScript, but a let statement can be used to achieve block-level scope effects

var a = 10;
{
let a = 100;
Console.log (a);//100
}
Console.log (a);//10

JS function Learning

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.