JavaScript Basics (v) function variables and scopes

Source: Internet
Author: User
Tags variable scope

function definition and invocation
Define a function, in JavaScript, to define the function in the following way:
function ABS (x) {
if (x >=0) {
return x;
}else{
Return-x;
}
}
The above definition of the ABS () function is as follows:
function indicates that this is a functional definition;
ABS is the name of the function;
(x) The parameters of the function are listed in parentheses, separated by multiple parameters;
{...} The code between is a function body, can contain several statements, and even can not have any statements.
NOTE: When the statement inside the function body executes, once it executes to return, the function finishes and returns the result. Thus the internal passing of conditional judgments and loops can be very complex in implementation.

If there is no return statement, the result is returned after the function is executed, except that the result is undefined.
Since the JavaScript function is 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 functions.     

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

In this way, function (x) {...} is an anonymous function that does not have a function name. However, this anonymous function assigns a value to the variable abs, so the function can be called by using the variable abs.
The two definitions are completely equivalent, note that the second way is to add one at the end of the function body according to the complete syntax, which means that the assignment statement ends.
When you call a function, you pass in the arguments sequentially:    

ABS (10); Returns 10
ABS (-9); Returns 9

Because JavaScript allows you to pass in any parameter without being affected by the call, there is no problem with the parameters passed in that are more than the parameters you define, although they are not required inside a function.
ABS (, ' Blablabla '); Returns 10
ABS ( -9, ' haha ', ' hehe ', NULL)//Return 9

There's no problem with passing in fewer parameters than you define
ABS (); Return Nan

At this point the ABS (x) function parameter x will receive the undefined, which evaluates to 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 free keyword, arguments, which works only inside the function and always points to all arguments passed in by the caller of the current function.
function foo (x) {
alert (x); 10
for (var i=0; i < arguments.length;++) {
Alert (Arguments[i]); 10,20,30
}
}
Foo (10.20,30)

With arguments, you can get all the arguments passed in by the caller. That is, even if the function does not define any parameters, it can get the value of the parameter:
function abs () {
if (Arguments.length ===0) {
return 0;
}
var x = arguments[0]
return x >=0? ×:-X;
}
ABS (); 0
ABS (10); 10
ABS (-9)//9

In fact, arguments is most commonly used to determine the number of incoming parameters. You may see the following notation:
Foo (a[,b],c)
Accept two or three arguments, B is an optional parameter, and B defaults to null if you enter or leave two parameters
function foo (a,b,c) {
if (Arguments.length ===2) {
The actual parameters obtained are A and B C for undefined
c = b;
b = null; b becomes the default value

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

Rest parameters
Since JavaScript functions allow the receipt of arbitrary parameters, we have to use arguments to get all the arguments:
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);
}

In order to get the parameters beyond the defined parameters A, B, we have to use arguments, and the loop to start at index 2 to exclude the first two parameters, this is very awkward, just to get extra rest parameters, there is no better way?

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

function foo (A, b,... rest) {
Console.log (' a = ' + a);
Console.log (' B = ' + B);
Console.log (rest);
}
Foo (1,2,3,4,5);
Results
A = 1
b = 2
array[3,4,5]
Foo (1)
Results
A = 1
b = undefined
Array []

The rest parameter can only be written at the end, preceded by ... indicator, from the running results, it is shown that the parameters passed in first bind a, B, the extra parameters are given to the variable rest in the array form, so,
We get all the parameters when we don't need arguments.
It does not matter if the passed parameters are not filled with the normal defined parameters, and the rest parameter receives an empty array (note that it is not undefined).

  

Return Statement
We talked about a JavaScript engine that has a mechanism for automatically adding semicolons at the end of a line, which might allow you to plant a hole in the return statement:,
function foo () {
Return {name: ' foo '};
}
foo ();//{name: ' foo '}
to note:
function foo () {
return://automatically adds a semicolon, Equivalent to return undefined
{name: ' foo '};//This line of statements is no longer able to execute.
}
So the correct multiline notation is
function foo () {
Return {//The semicolon is not automatically added here because the statement is not yet finished.
Name: ' foo '
}
}

Variable scope
In JavaScript, the declaration of VAR is actually scoped.
If a variable is declared within the body of a function, the variable is scoped to the entire function body and should not be referenced outside the body of the function.
' Use strict ':
function foo () {
var x = 1;
x = x +1;
}
x = x +2; Refrenceerror cannot reference the variable x outside the body of the function
if two different functions declare the same variable, the variable works only in the body of the function. In other words, the same name variables inside different functions are independent from 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, an intrinsic function can access variables defined by an external function, which in turn does not:
' Use strict ';
function foo () {
var x = 1;
function Bar () {
var x = 1;
function Bar () {
var y= x +1; Bar can access the variable x of foo
}
var z = y + 1; refernceerror! Foo does not have access to the bar's variable y!
}
}

What if the names of the variables for the intrinsic and external functions are identical?

' Use strict ':
function foo () {
var x = 1;
function Bar () {
var x = ' A ';
Alert (' X in bar () = ' + x '); A
}
Alert (' X in foo () = ' +x)//1
Bar ();
}

Variable Promotion
JavaScript's function definition has a feature that scans the entire function body's statement 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 Foo () function above, the JavaScript engine sees the code equivalent to:
function foo () {
var y; The elevation of the variable y
var x = ' Hello ' + y;
alert (x);
y = ' Bob ';
}

Because of this bizarre "feature" of JavaScript, when we define variables inside a function, strictly abide by the "first declaration of all variables within a function" rule. The most common practice is to declare all the variables used inside the function with a var:
function foo () {
var x =1,//x initialized to 1
y = x +1,//y initialized to 2
z,i;//Z and I are undefined
Other statements
for (i =0; i<100; i++) {
...
}
}

Global scope
Variables that are not defined within any function have global scope, and in fact, JavaScript has a global scope variable that is actually bound to a property of window.
' Use strict ';
var sourse = ' Learn JavaScript ';
Alert (course); ' Learn JavaScript ';
alert (window.course); ' Learn JavaScript '

Name space
Global variables are bound to the window, and different JavaScript files use the same global variables, or the top-level function that defines the same name, will cause
Naming conflicts, and is difficult to find,
One way to reduce the conflict is to bind all of your variables and functions to a global variable.
The only Quju opera variable, MyApp
var MYAPP = {};
Other variables:
Myapp.name = ' MyApp ';
Myapp.version = 1.0;

Other functions
Myapp.foo = function () {
Return ' foo ';
};

Putting all of your code into a unique namespace, MyApp, will greatly reduce the likelihood of global variable collisions.
Local scope
Since the variable scope of JavaScript is actually inside the function, we cannot define a variable with a local scope in a statement block such as a For loop.
function foo () {
for (var i = 0; i<100; i++) {
//
}
i+=100; Variables can still be referenced;
}

To solve block-level scopes, ES6 introduces a new keyword let, which can be used to declare a block-scoped variable by substituting Var:
function foo () {
var sum = 0;
for (let i=0; i<100;i++) {
Sum +=i;
}
I +=1;
}

Constant
Because of Var and let declared variables, if you want to declare a constant, before ES6 is not possible, we usually use the full capitalization of the variable two to indicate that this is a constant
Don't change his value.
var PI = 3.14;
The ES6 standard introduces a new keyword const to define constants, and both const and let have block-level scopes;
Const PI = 3.14;
PI = 3;//Some browsers do not error, but no effect.
PI; 3.14

JavaScript Basics (v) function variables and scopes

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.