Function definition and call
Defining functions. In JavaScript, the way to define functions is as follows:
function abs(x){ if(x >=0){ return x;}else{ return -x;}}The above abs() function is defined as follows:
function indicates that this is a function definition;
abs is the name of the function;
(x) List the parameters of the function in brackets, separated by multiple parameters;
The code between {...} is a function body, which can contain several statements, or even without any statement.
Note: When the statement inside the function body is executed, once it is executed to return, the function is executed and the result is returned. Therefore, the internal determination and loop can be implemented very complexly.
If there is no return statement, the result will be returned after the function is executed, but the result is undefined.
Since JavaScript's 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 function.
var abs = function(x){ if(x >= 0){ return x;} else { return -x;}}In this way, function (x) { ... } is an anonymous function that has no function name. However, this anonymous function is assigned to the variable abs, so the function can be called through the variable abs.
The two definitions are completely equivalent. Note that the second method needs to add one at the end of the function body according to the complete syntax, indicating that the assignment statement ends.
When calling a function, just pass in the parameters in order:
abs(10); // Return 10
abs(-9); // Return to 9
Since JavaScript allows any parameter to be passed without being affected, there is no problem that there are more parameters passed than defined parameters, although these parameters are not required within the function.
abs(10,'blablabla'); //Return 10
abs(-9,'haha','hehe',null) // Return to 9
There is no problem with fewer parameters than defined
abs(); Return NaN
At this time, 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 free keyword arguments, which only works inside the function and always points to all parameters passed in 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 get all the parameters passed by the caller. That is to say, even if the function does not define any parameters, the value of the parameter 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) //9In fact, arguments are most commonly used to determine the number of incoming parameters. You may see this writing:
// foo(a[,b],c)
// Accept 2~3 parameters, b is an optional parameter. If only two parameters are entered and exited, b is null by default
function foo(a,b,c){ if(arguments.length ===2){ // The actual parameters obtained are a and bc are undefinedc = b;b = null; // b becomes the default valueTo change the middle parameter b into an "optional" parameter, you can only judge it through arguments, then readjust the parameters and assign values.
rest parameter
Since JavaScript functions allow to receive any parameter, we have to use arguments to obtain all parameters when encountering 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);}In order to obtain parameters other than defined parameters a and b, we have to use arguments, and the loop starts from index 2 to exclude the first two parameters. This writing method is awkward, just to get the extra rest parameter. Is there a better way?
The ES6 standard introduces the rest parameter, and the above function 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);//Result// a = 1// b = 2// Array[3,4,5]foo(1)// Result// a = 1// b = undefined// Array []The rest parameter can only be written at the end, and is marked with... from the run result. From the operation result, we can see that the passed parameters are bound to a, b, and the extra parameters are handed over to the variable rest in an array, so,
We get all the parameters without requiring arguments.
If the passed parameters are not filled with normal defined parameters, it doesn't matter, the rest parameter will receive an empty array (note that it is not undefined).
return statement
We mentioned earlier that the JavaScript engine has a mechanism to automatically add semicolons at the end of the line, which may cause you to fall into a big pit in the return statement:
function foo(){ return {name:'foo'};}foo(); // {name:'foo'}Note:
function foo(){ return: //A semicolon was added automatically, which is equivalent to return undefined{name:'foo'}; // This line of statement can no longer be executed. }So the correct way to write multiple lines is
function foo(){ return { // A semicolon will not be automatically added here because it means that the statement has not ended yet. name:'foo'}}Variable scope
In JavaScript, what is declared with var is actually scoped.
If a variable is declared inside the function body, the scope of the variable is the entire function body, and the variable should not be referenced outside the function body.
'use strict':function foo(){ var x = 1;x = x +1;}x = x +2; // RefrenceError Cannot refer to the variable x outside the functionIf two different functions each declare the same variable, then the variable only works within the body of their respective functions. In other words, variables with the same name within 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';}Since JavaScript functions can be nested, the internal function can access variables defined by external functions, and the other way around is 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 z = y + 1; //ReferenceError! foo cannot access the variable y of bar! }}What if the variable names of internal and external functions are doubled?
'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 enhancement
JavaScript's function definition has a feature, which will first scan the entire function body statement and "upgrade" 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 code seen by the JavaScript engine is equivalent to:
function foo(){ var y; // Raise the var x of the variable y = 'Hello' + y;alert(x);y = 'Bob';}Due to this weird "characteristic" of JavaScript, when we define variables inside a function, please strictly abide by the rule "to declare all variables first within a function". The most common way is to use a var to declare all variables used internally 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, JavaScript has a global scoped variable by default that is actually bound to a property of the window.
'use strict';var source = 'Learn JavaScript';alert(course); // 'Learn JavaScript';alert(window.course); // 'Learn JavaScript'
Namespace
Global variables will be bound to window. Different JavaScript files use the same global variables, or have the same name top-level functions, which will cause
Naming conflicts and are difficult to detect.
One way to reduce conflict is to bind all your variables and functions into a global variable.
// The only Quju 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
Since JavaScript's variable scope is actually inside a function, we cannot define variables that cannot be defined in statement blocks such as for loops.
function foo(){ for(var i = 0; i<100; i++){ //}i+=100; // variables can still be referenced;}To solve the block-level scope, ES6 introduced a new keyword let, and instead of var, you can declare a block-level scope variable:
function foo(){ var sum = 0;for(let i=0; i<100;i++){ sum +=i;}i +=1;}constant
Since var and let declare variables, if you want to declare a constant, it will not work before ES6. We usually use all capital variables to indicate that this is a constant
Don't modify its value.
var PI = 3.14;
The ES6 standard introduces a new keyword const to define constants, both const and let have block-level scope;
const PI = 3.14;
PI = 3; // Some browsers do not report errors, but have no effect.
PI; // 3.14
The above JavaScript basic functions_In-depth analysis of variables and scope is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.