JavaScript function definitions
JavaScript uses the keyword function to define functions
A function can be declaratively defined or can be an expression
Function declaration Syntax for function declaration:
function sum1(n1,n2){
return n1+n2;
};
Copy the code
Functions are not executed immediately after they are declared; they are called when we need them
Semicolons are used to separate executable JavaScript statements and do not end with semicolons since function declarations are not executable statements
Function expressions, also called function literals JavaScript functions can be defined by an expression
Function expressions can be stored in variables:
var sum2=function(n1,n2){
return n1+n2;
};
Copy the code
After the function expression is stored in the variable, the variable can also be used as a function:
The difference: the parser reads the function declaration and makes it accessible before any code is executed; Functional expressions, on the other hand, cannot be interpreted until the parser reaches its line of code.
var x = function (a, b) {return a * b};
var z = x(4, 3);
Copy the code
The above function is actually an anonymous function (the function has no name). Functions are stored in variables, do not need function names, and are usually called by variable names. The above function ends with a semicolon because it is an execution statement.
Function 1: function 1: function 1: function
function Test(){
alert("test");
}
Test()
Copy the code
2 Anonymous functions:
var test=function(){
alert("test");
}
test();
Copy the code
3 self-calling function:
(function () { alert('test'); }) ();Copy the code
4 Function nesting:
var Test = {
test1:function(){
alert('test1');
},
test2:function(){
alert('test2');
}
}
var t = Test.test1();
Copy the code
Function inheritance and constructors
var Test = function(){};
Test.prototype={
test1:function(){
alert('test1');
},test2:function(){
alert('test2');
}
}
var t = new Test();
t.test2();
Copy the code
In the above example, we saw that functions are defined by the keyword Function. Functions can also be defined using the built-in JavaScript Function constructor (Function())
var myFunction = new Function("a", "b", "return a * b");
var x = myFunction(4, 3);
Copy the code
In fact, you don’t have to use constructors. The above example can be written as:
var myFunction = function (a, b) {return a * b}
var x = myFunction(4, 3);
Copy the code
In JavaScript, a lot of times, you want to avoid using the new keyword
As of July 1, 1997, function promotion is the default action of JavaScript to promote the current scope back to the front.
Ascending (as) applies in variable declaration as in function declaration, so that functions can be called prior to the declaration:
myFunction(5);
function myFunction(y) {
return y * y;
}
Copy the code
Cannot be promoted when defining functions using expressions
myFunction(5);
var myFunction = function(y) {
return y * y;
}
Copy the code
The above code runs with an error because the function is in an initialization statement, not a function declaration. In other words, no reference to the function is stored in the variable myFunction until the function statement is executed; Also, since the first line of code would cause an “unexpected identifier” error, it would not actually go to the next line.
The syntax of a function declaration is equivalent to that of a function expression, except that a function can be accessed through a variable when declared.
Self-calling function Function expressions can be “self-calling”. Self-calling expressions are automatically called. If the expression is immediately followed by (), it is automatically called. Declared functions cannot be called by themselves. To indicate that it is a function expression, add parentheses:
(function () { var x = "Hello!!" ; // I'll call myself})();Copy the code
The above function is actually an anonymous self-calling function
Self-calling functions can be used to pass parameters with return values
var sum=(function(x,y){ return x+y; }) (2, 3); console.log(sum);Copy the code
Strictly speaking, self-executing functions are also called function expressions. They are mainly used to create a new scope. Variables declared in this scope do not conflict with or confuse variables in other scopes.
A JavaScript function can be used as a value
function myFunction(a, b) {
return a * b;
}
var x = myFunction(4, 3);
Copy the code
JavaScript functions can be used as expressions:
function myFunction(a, b) {
return a * b;
}
var x = myFunction(4, 3) * 2;
Copy the code
A function is an object. Determining the typeof a function using the typeof operator in JavaScript returns “function”, but it is more accurate to describe a JavaScript function as an object.
JavaScript functions have properties and methods.
The arguments.length property returns the number of arguments received during the function call:
function myFunction(a, b) { return arguments.length; } the document. The getElementById (" demo "). The innerHTML = myFunction (4,3,6,5);Copy the code
The toString() method returns the function as a string:
Function definitions, as properties of objects, are called object methods.
The function used to create a new object is called the object’s constructor
JavaScript functions do not check the arguments’ values
Function explicit arguments are listed at the time of the function definition
functionName(parameter1, parameter2, parameter3) {
code to be executed
}
Copy the code
Function hidden arguments are passed to the function with the real value when the function is called
JavaScript functions are defined with no data type specified for arguments, no check for hidden arguments, and no check for the number of arguments
Default Argument If the function is called without an argument, the argument defaults to undefined
Sometimes this is acceptable, but it is advisable to set a default value for the parameter:
function myFunction(x, y) { if (y === undefined) { y = 0; }}Copy the code
Or, simpler:
function myFunction(x, y) {
y = y || 0;
}
Copy the code
If y have been defined, y | | return y, because y is true, otherwise it returns 0, because of the undefined to false
If a function is called with too many parameters, the parameters cannot be referenced because the corresponding parameter name cannot be found. Can only be called using arguments objects
JavaScript functions have a built-in object called Arguments object. The Arguments object contains an array of arguments to the function call. This way you can easily find the value of each parameter:
x = findMax(1, 123, 500, 115, 44, 88);
function findMax() {
var i, max = 0;
for (i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
Copy the code
Or create a function to count the sum of all values:
x = sumAll(1, 123, 500, 115, 44, 88);
function sumAll() {
var i, sum = 0;
for (i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
Copy the code
Parameters passed by value The parameters called in a function are the parameters of the function. If a function modifies the value of an argument, its initial value (defined outside the function) is not modified.
var x = 1; Function myFunction(x) {// pass the argument x++; // Change the value of parameter x, will not change the variable x console.log(x) defined outside the function; } myFunction(x); // 2 console.log(x); / / 1Copy the code
Passing arguments through objects can refer to the value of an object in JavaScript, so modifying an object’s properties inside a function changes its original value. Modifying object properties can be applied outside of functions (global variables).
var obj = {x:1}; Function myFunction(obj) {// pass the argument obj. X++; // Change the value of the argument object obj.x, and the obj defined outside the function will also be changed console.log(obj.x); } myFunction(obj); // 2 console.log(obj.x); / / 2Copy the code
JavaScript functions can be called in four ways. The difference between each method is the initialization of this
Generally speaking, in Javascript, this refers to the current object at the time the function is executed
Note that this is a reserved keyword and you cannot change the value of this
Calling JavaScript functions The code in a function is executed after the function is called
Called as a function
function myFunction(a, b) {
return a * b;
}
Copy the code
myFunction(10, 2); // myFunction(10, 2) returns 20 or more functions that do not belong to any object. But it is always the default global object in JavaScript.
The default global object in HTML is the HTML page itself, so functions belong to the HTML page.
The page object in the browser is the browser window object. The above functions automatically become functions of the window object
MyFunction () is the same as window.myfunction () :
function myFunction(a, b) { return a * b; } window.myFunction(10, 2); // window.myfunction (10, 2) returns 20Copy the code
This is a common way to call JavaScript functions, but it’s not good programming practice. Bugs that cause naming conflicts for global variables, methods, or functions
Global object The value of this becomes a global object when the function is not called by its own object.
In a Web browser, the global object is the browser window object.
This instance returns the value of this as the window object:
function myFunction() { return this; } myFunction(); // Returns the window objectCopy the code
The function is called as a global object, making the value of this a global object. Using a window object as a variable can crash programs
Functions called as methods In JavaScript you can define functions as methods of objects.
The following example creates an object (myObject) with two attributes (firstName and lastName) and a method (fullName):
var myObject = { firstName:"John", lastName: "Doe", fullName: function () { return this.firstName + " " + this.lastName; } } myObject.fullName(); // return "John Doe"Copy the code
The fullName method is a function. Functions belong to objects. MyObject is the owner of the function.
This object has JavaScript code. The value of this in this instance is myObject. Test the following! Modify the fullName method and return this:
var myObject = { firstName:"John", lastName: "Doe", fullName: function () { return this; } } myObject.fullName(); // Return [object object] (owner object)Copy the code
The function is called as an object method, making the value of this the object myObject itself
When a function is called using a constructor, the arguments must be quoted. If the function is called with the new keyword, the constructor is called. This looks like creating a new function, but JavaScript functions are actually recreated objects:
// Constructor: function myFunction(arg1, arg2) {this.firstName = arg1; this.lastName = arg2; } // This creates a new object var x = new myFunction("John","Doe"); x.firstName; / / return "John"Copy the code
The constructor call creates a new object. The new object inherits the properties and methods of the constructor
The constructor does not have any value for this keyword. The value of this is created when the new object is instantiated during the function call.
Calling a function as a function method In JavaScript, functions are objects. JavaScript functions have their properties and methods. Call () and apply() are predefined function methods. Two methods can be used to call functions, and the first argument of both methods must be the object itself.
//call() function myFunction(a, b) { return a * b; } myFunction.call(myObject, 10, 2); //apply() function myFunction(a, b) {return a * b; } myArray on = [10, 2]; myFunction.apply(myObject, myArray); / / return 20Copy the code
Both methods take the object itself as the first argument. The difference is in the second argument: Apply passes in an array of arguments, combining multiple arguments into one array, while call is passed in as an argument to call (starting with the second argument). The first argument to call and apply is the object to which the this pointer points
In JavaScript strict mode, the first argument becomes the value of this when a function is called, even if the argument is not an object.
In JavaScript non-strict mode, if the value of the first parameter is null or undefined, it is replaced with a global object.
With the call() or apply() methods you can set the value of this and call it as a new method on an existing object
JavaScript variables can be local or global
Private variables can use closures
Local and global variable functions can access variables defined inside the function
function myFunction() {
var a = 4;
return a * a;
}
Copy the code
Functions can also access variables defined outside the function
var a = 4;
function myFunction() {
return a * a;
}
Copy the code
In the latter example, a is a global variable. In web pages, global variables belong to window objects. Global variables can be applied to all scripts on the page.
In the first instance, a is a local variable. Local variables can only be used to define the inside of their functions. The code is not available for other functions or scripts. Global and local variables are two different variables even if they have the same name. Modifying one does not affect the value of the other.
The variable declaration is that if you do not use the var keyword, it is a global variable, even if it is defined within a function
The scope of a global variable is global, meaning that it is present everywhere in a JavaScript program. Variables declared inside a function, on the other hand, only work inside the function. These variables are local variables whose scope is local. The parameters of a function are also local, acting only inside the function.
Counter dilemma Imagine if you wanted to count some value and the counter was available in all functions. You can increment the counter using global variables:
var counter = 0; function add() { counter += 1; } add(); add(); add(); // The counter is now 3Copy the code
The counter value changes when the add() function is executed. The problem is that any script on the page can change the counter, even without calling add(). If I declare a counter inside a function, I cannot change the value of the counter without calling the function:
function add() { var counter = 0; counter += 1; } add(); add(); add(); // Instead of printing 3, you can print 1!Copy the code
The above code will not print correctly, and every time I call add(), the counter will be set to 1. JavaScript embedded functions can solve this problem
JavaScript embedded functions All functions have access to global variables. In fact, in JavaScript, all functions have access to the scope at the level above them. JavaScript supports nested functions. Nested functions can access function variables at the upper level.
In this example, the inline function plus() has access to the parent function’s counter variable:
function add() { var counter = 0; function plus() {counter += 1; } plus(); return counter; }Copy the code
If we could access the plus() function externally, this would solve the counter dilemma. We also need to make sure that counter = 0 is only executed once. We need closures.
JavaScript closures
var add = (function () { var counter = 0; return function () {return counter += 1; }}) (); add(); add(); add(); // The counter is 3Copy the code
The add variable specifies the return word value for the function’s self-call. A self-calling function is executed only once. Set the counter to 0. And returns the function expression. The add variable can be used as a function. The cool part is that it has access to the counters in the scope above the function. This is called a JavaScript closure. It makes it possible for functions to have private variables. Counters are protected by the scope of anonymous functions and can only be modified by the add method.