Basic JavaScript function _ in-depth analysis of variables and scopes, and in-depth analysis of javascript

Source: Internet
Author: User
Tags variable scope

Basic JavaScript function _ in-depth analysis of variables and scopes, and in-depth analysis of javascript

Function Definition and call

Define a function. In JavaScript, the method for defining a function is as follows:

function abs(x){ if(x >=0){ return x;}else{ return -x;}}

The abs () function is defined as follows:

Function indicates that this is a function definition;

Abs is the name of the function;

(X) list function parameters in parentheses. Multiple parameters are separated by commas;

The code between {...} is the function body, which can contain several statements or even no statements.

Note: When executing a statement in the function body, once return is executed, the function is executed and the result is returned. Therefore, it can be very complicated to implement through conditional judgment and loops.

If there is no return statement, the result is returned after the function is executed, but the result is undefined.

Because JavaScript Functions are also an object, the abs () function defined above is actually a function object, and the function name abs can be regarded as a variable pointing to the function.

var abs = function(x){ if(x >= 0){ return x;} else { return -x;}}

In this way, function (x) {...} is an anonymous function with no function name. However, this anonymous function is assigned to the variable abs, so you can call this function through the variable abs.

The two definitions are completely equivalent. Note that the second method requires adding one at the end of the function body according to the complete syntax, indicating that the value assignment statement ends.

When calling a function, you can input parameters in sequence:

Abs (10); // return 10
Abs (-9); // return 9

Because JavaScript allows the input of any parameter without affecting the call, there is no problem in passing in more parameters than the defined parameters, although these parameters are not required inside the function.

Abs (10, 'blablabl'); // return 10
Abs (-9, 'hahaha', 'hehe ', null) // return 9

The number of input parameters is smaller than that defined.

Abs (); returns NaN

In this case, the parameter x of the abs (x) function will receive undefined, and the calculation result is NaN.

function abs(x){ if(typeof x !=='number'){ throw 'Not a number':} if(x >=0){ return x;}else{ return -x;}}

Arguments

JavaScript also has a complimentary keyword arguments, which only works within the function and always points to all parameters passed by the caller of the current function.

function foo(x){ alert(x); // 10for(var i=0; i < arguments.length;++){ alert(arguments[i]); // 10,20,30}}foo(10.20,30)

With arguments, you can obtain all parameters passed by the caller. That is to say, even if the function does not define any parameters, the parameter value can still be obtained:

function abs(){ if(arguments.length ===0){ return 0;}var x = arguments[0]return x >=0 ? x : -x;}abs(); //0abs(10); // 10abs(-9) //9

In fact, arguments is most commonly used to determine the number of input parameters. You may see the following statement:

// Foo (a [, B], c)

// Accept 2 ~ Three parameters. B is an optional parameter. If two parameters are input or output, B is null by default.

Function foo (a, B, c) {if (arguments. length = 2) {// The actual obtained parameters a and B c are undefinedc = B; B = null; // B is changed to the default value.

To change the intermediate parameter B to an "optional" parameter, you can only use arguments to determine the parameter, and then re-adjust the parameter and assign a value.

Rest Parameters

Because JavaScript Functions allow receiving arbitrary parameters, we have to use arguments to obtain all the parameters in case of such problems:

function foo(a,b){ var i, rest = [];if(arguments.length > 2){ for(i = 2; i < arguments.length; i++){ rest.push(arguments[i]);}}console.log('a =' + a);console.log('b = ' + b);console.log(rest);}

To obtain parameters other than the defined parameters a and B, we have to use arguments and the loop starts from index 2 to exclude the first two parameters, is there a better way to obtain additional rest parameters?

The ES6 standard introduces the rest parameter. The above function can be rewritten:

Function foo (a, B ,... rest) {console. log ('a = '+ a); console. log ('B =' + B); console. log (rest);} foo (, 5); // result // a = 1 // B = 2 // Array [, 5] foo (1) // result // a = 1 // B = undefined // Array []

Rest parameters can only be written at the end, marked with.... From the running results, we can see that the input parameters are first bound to a, B, and redundant parameters are passed to the variable rest in the form of an array. Therefore,

We do not need arguments to obtain all the parameters.

If the input parameter is not fully filled with the normally defined parameter, the rest parameter will receive an empty array (note that it is not undefined ).

Return Statement

As we mentioned above, the JavaScript engine has a mechanism to automatically add semicolons at the end of a row, which may cause you to plant a big pitfall in the return statement :,

function foo(){ return {name:'foo'};}foo(); // {name:'foo'}

Note:

Function foo () {return: // a semicolon is automatically added, which is equivalent to return undefined {name: 'foo'}; // This line of statements cannot be executed .}

So the correct method for writing multiple lines is:

Function foo () {return {// no extra points will be given here, because the statement has not ended. Name: 'foo '}}

Variable Scope

In JavaScript, the Declaration with var is actually scoped.

If a variable is declared inside the function body, the scope of the variable is the whole function body, and the variable should not be referenced in the function body.

'Use strict ': function foo () {var x = 1; x = x + 1;} x = x + 2; // RefrenceError cannot reference this variable x in vitro.

If two different functions declare the same variable, the variable takes effect only in the corresponding function. In other words, variables with the same name in different functions are independent of each other and do not affect each other:

'use struct':function foo(){ var x = 1;x = x +1;}function bar (){ var x= 'A';x = x + 'B';}

Because JavaScript functions can be nested, internal functions can access variables defined by external functions, but not the following:

'Use strict '; function foo () {var x = 1; function bar () {var x = 1; function bar () {var y = x + 1; // bar can access the foo variable x} var z = y + 1; // RefernceError! Foo cannot access the bar variable y !}}

What if the variable names of the internal and external functions are the same?

'use strict':function foo(){ var x = 1;function bar (){ var x = 'A';alert('x in bar() =' + x); // 'A'}alert('x in foo()=' +x) //1bar();}

Variable increase

The Function Definition of JavaScript has a feature. It first scans the statements of the entire function body and "promotes" all declared variables to the top of the function:

'use strict';function foo(){ var x='Hello,'+y;alert(x);var y = 'Bob';}foo();

For the above foo () function, the JavaScript engine sees the code equivalent:

Function foo () {var y; // var x = 'hello' + y; alert (x); y = 'bob ';}

Because of this weird "feature" of JavaScript, when we define variables in a function, strictly abide by the rule "declare all variables in the function first. The most common practice is to use a var statement to declare all the variables used in the function:

Function foo () {var x = 1, // x is initialized to 1y = x + 1, // y is initialized to 2z, I; // z and I are undefined // other statements for (I = 0; I <100; I ++ ){...}}

GLOBAL SCOPE

Variables not defined in any function have a global scope. In fact, by default, JavaScript has a global scope variable which is actually bound to an attribute of window.

‘use strict';var sourse = 'Learn JavaScript';alert(course); // 'Learn JavaScript';alert(window.course); // 'Learn JavaScript'

Namespace

Global variables are bound to Windows. Different JavaScript files use the same global variables or top-level functions with the same name.

Naming conflicts are difficult to detect,

One way to reduce conflicts is to bind all your variables and functions to a global variable.

// The unique Qu opera variable MYAPPvar MYAPP ={}; // other variables: MYAPP. name = 'myapp'; myapp. version = 1.0; // other functions: MYAPP. foo = function () {return 'foo ';};

Putting all your code into the unique namespace MYAPP will greatly reduce the possibility of global variable conflicts.

Local Scope

Because the scope of JavaScript variables is actually inside the function, we cannot define variables with local scopes in the for loop or other statement blocks.

Function foo () {for (var I = 0; I <100; I ++) {//} I + = 100; // variables can still be referenced ;}

To solve block-level scope, ES6 introduces a new keyword let. Replacing var WITH let can declare a block-level scope variable:

function foo(){ var sum = 0;for(let i=0; i<100;i++){ sum +=i;}i +=1;}

Constant

Because of the variables declared by var AND let, if you want to declare a constant, it won't work before ES6. We usually use both variables in uppercase to indicate that this is a constant.

Do not modify its value.

Var PI = 3.14;
ES6 standard introduces a new keyword const to define constants. Both const and let have block-level scopes;
Const PI = 3.14;
PI = 3; // Some browsers do not report errors, but they do not work.
PI, // 3.14

The above JavaScript basic function _ in-depth analysis of variables and scopes is all the content shared by the editor. I hope to give you a reference, and hope you can also support the help house.

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.