Create a function
A function is a special kind of function
// A named function
function fn(x, y) {
return x + y
}
// Anonymous function
function (x, y) {
return x + y
}
// Arrow function
let a = x= > x * x
let a2 = (x, y) = > {
console.log('hi! ');
return x + y
}
let a3 = x= > ({
name: x
})
Copy the code
Elements of a function
Call time
let i = 0
for(i = 0; i<6; i++){
setTimeout(() = >{
console.log(i)
},0) // Execute console.log(I) immediately
}
// Prints six 6's
Copy the code
Let’s start with the setTimeout() method: It sets a timer that executes a function or a specified piece of code when the timer expires. SetTimeout () is an asynchronous task. The for loop is a synchronous task. The asynchronous task can be executed only after the synchronous task has been completed. I = 6 after executing the loop, and then executing the arrow function in setTimeout. Print out I, which is 6. So I’m printing six 6’s.
Tell him to print 0, 1, 2, 3, 4, 5
Execute the following code
for( let i = 0; i<6; i++){
setTimeout(()=>{
console.log(i)
},0)
}
Copy the code
In the case of let in the for loop, I exists independently during each iteration due to the influence of block-level scope. So these six cycles I independently give us 0, 1, 2, 3, 4, 5, 6.
Other methods
function fn1() {
for (var i = 0; i < 6; i++) {
function fn2(i) {
setTimeout(() = > {
console.log(i)
}, 0) } fn2(i); }}Copy the code
Here fn2 refers to the variables of the external function to form a closure. In the closure state, the variable I is always kept in memory, and each call is evaluated on the basis of the previous call.
scope
JavaScript has only two types of scope: a global scope, where variables exist throughout the program and can be read anywhere; The other is function scope, where variables exist only inside a function.
Variables declared in the top-level scope are global variables
The properties of the window are global variables
Everything else is local
A local variable
function fn(x){
let a = 1
x=a
}
console.log(a);
// a is not defined
Copy the code
The global variable
var a = 1;
function f() {
console.log(a);
}
f()
/ / 1
Copy the code
Scope independent of function execution is static scope
var a = 1;
var x = function () {
console.log(a);
};
function f() {
var a = 2;
x();
}
f() / / 1
Copy the code
Function x is declared outside function F, so its scope-bound variables inside function x are not evaluated inside function F.
closure
Closures are simply understood as “functions defined inside a function.”
If a function uses an external variable, then the function plus that variable is called a closure.
Normally, variables declared inside a function cannot be read outside the function. If, for whatever reason, you want to get local variables in the function. Normally, this is not possible and can only be achieved through workarounds. That is, inside the function, define another function.
All variables of the parent object are visible to the child object, but not the other way around.
function f1(){
let a = 1
function f2(){
let a = 2
function f3(){
console.log(a) // a here calls a outside
}
a = 22
f3()
}
console.log(a)
a = 100
f2()
}
f1()
/ / 1
/ / 22
Copy the code
The above code only explains the following F2 and F3; Function f3 is inside function f2 when all local variables inside F2 are visible to F3.
Since F3 can read local variables of F2, we can read internal variables outside of F1 as long as f3 is returned.
A closure is useful for reading variables inside an outer function, and for keeping those variables in memory at all times. A closure is useful for keeping the environment in which it was created.
function fn(item) {
return function () {
return item++;
};
}
var inc = fn(5);
inc() // 5
inc() // 6
inc() // 7
Copy the code
The above code item is an internal variable of FN, which is retained in the closure state, and each call is evaluated on the basis of the previous call. The closure inc makes the internal environment of the function fn always exist. So, a closure can be thought of as an interface to a function’s internal scope.
Formal parameters
When a function is running, it sometimes needs to provide external data. Different external data will get different results. This external data is called parameter.
function add(x, y){
return x+y
}
// where x and y are parameters, since they are not actual arguments
add(1.2)
// When add is called, 1 and 2 are the actual arguments assigned to x and y
Copy the code
Parameters are essentially variable declarations
The return value
Every function has a return value until it executes
Undefined is returned without return
The call stack
What is the call stack
- JS engine before calling a function
- You need to push the function’s environment into an array
- This array is called the call stack
- When the function completes, it pops the environment out
- Then return to the previous environment and continue with the subsequent code
Burst stack
If too many frames are pushed into the call stack, the program will crash
Function name promotion
f()
function fn(){}
// No matter where you declare the named function, it will go to the first line
Copy the code
On the surface, the above code appears to call f before the declaration. But in reality, function F is promoted to the code header due to “variable promotion”, which is declared before the call. However, iF you define a function using an assignment statement, JavaScript will report an error.
f();
var f = function (){};
// TypeError: undefined is not a function
var f;
f();
f = function () {};
Copy the code
In line 2 of the code above, when I call f, it’s just declared, it’s not assigned yet, it’s equal to undefined, so I get an error.
Arguments (except for arrow functions)
Arguments is a pseudo-array
Because JavaScript allows functions to have an indefinite number of arguments, you need a mechanism to read all of the arguments inside the function body. That’s where arguments objects come from.
This (except for the arrow function)
This will point to the window by default if you don’t condition this
function fn(){
console.log(this)
}
fn()
// outputs Window {Window: Window, self: Window, document: document, name: "", location: location,... }
Copy the code
If this is not an object that JS will automatically wrap as an object
Call (XXX, 1,2,3)
function fn(){
'use strict' ; // Keep this in strict mode so it doesn't become an object
console.log(this)}Copy the code
This is the hidden parameter
Arguments are common arguments
let person = {
name: 'frank'.sayHi(this){
console.log('Hello, my name is' + this.name)
}
}
person.sayHi()
/ / equivalent to
person.sayHi(person)
// person.sayhi () implicitly passes person to sayHi as this
// Then person is passed to this (person is an address)
// Each function can use this to get a reference to an unknown object
Copy the code
This is the object on which the function is called
.call
function add(x,y){
return x+y
}
add.call(null.1.2)
Copy the code
Why do I write undefined
- Because the first argument is going to be this
- But this is not in the code
- So you can only use undefined as a placeholder
- You can also use null
Array.prototype.forEach = function(){
console.log(this);
}
let arr = [1.2.3]
arr.forEach.call(arr) // arr is this
// forEach source code traverses the current array
Array.prototype.forEach = function(fn){
for(let i = 0; i<this.length; i++){ fn(this[i],i)
}
}
arr.forEach.call(arr.(item)=> conaole.log(item))
Copy the code
Arrow function
console.log(this) // window
let fn = () = > console.log(this)
fn() // window
Copy the code
Execute function immediately
!function () { /* code */} (); ~function () { /* code */} (); -function () { /* code */} (); +function () { /* code */} ();Copy the code
Source: Hungry Valley Javascript Tutorial – Webpath
This article is the original article, the copyright belongs to myself and hunrengu, must indicate the source of reprint