当前位置:网站首页>JS deep understanding of functions
JS deep understanding of functions
2022-06-24 18:36:00 【Brother Mengfan】
Catalog
One 、 Declaration of functions
1.2、 Function expression ( Anonymous functions )
2.3、 The difference between a custom function call and a function expression call
3、 ... and 、 Function parameter
5、 ... and 、 Internal properties of a function
6.3、call() and apply() Application
6.3.1、 Find the largest element in the array
6.3.2、 Convert a pseudo - class array to a real array
6.3.4、 utilize call and apply Do inheritance
7、 ... and 、 Immediate execution function
7.2、 Execute the function application immediately
One 、 Declaration of functions
1.1、 Custom function
Grammar format :
function The name of the function ( parameter list ) {
The body of the function
[return value ]
}
Be careful :
(1)function Keywords that are declarative functions must be lowercase ;
(2)function Keyword must be followed by function name , Function names generally use the verb , Need to conform to naming rules ;
(3) The function name is followed by a pair of parentheses , Parentheses followed by a pair of braces , Inside the braces is the function body .
1.2、 Function expression ( Anonymous functions )
Grammar format :
var Reference function name = function( parameter list ) {
The body of the function
[return value ]
}
Be careful :
(1) To declare a function as a function expression, you still need to use function keyword ;
(2)function Keyword followed by a pair of parentheses , Parentheses followed by a pair of braces , Inside the braces is the function body ;
(3) Since this defined function has no name , So you need to assign a function to a variable .
Two 、 Function call
2.1、 Custom function call
Use the function name to call
// Declare functions
function myFunction() {
}
// Call function
myFunction();
2.2、 Function expression call
You need to call... By function variable name
// Declare functions
var myFunction = function() {
}
// Call function
myFunction();
2.3、 The difference between a custom function call and a function expression call
<script>
fn1();
function fn1() {
console.log('fn1');
}
fn2();// Report errors
var fn2 = function() {
console.log('fn2');
};
</script>
difference :
(1) If it is a function declared by a user-defined function , You can call... Before and after you declare a function statement ; If it is a function expression to declare the function , Can only be called after a declaration statement , Cannot call... Before a statement is declared .
(2) For functions declared in a custom function mode , Use Function name To call ; For functions declared in the form of function expressions , You need to go through functions Variable name To call .
3、 ... and 、 Function parameter
function The name of the function ( Parameter list ){
The body of the function
}
The name of the function ( Argument list );

Example :
<script>
function add(a, b) {
console.log(a, b);
return a + b;
}
var result = add(2, 3); //2 3
console.log(result); //5
result = add(4, 6, 9); // 4 6
console.log(result); //10
result = add(5); //5 undefined
console.log(result); //5+undefined=NaN
</script>
Running results :
Be careful :
(1) Formal parameters do not need var Declare variables , Otherwise, an error will be reported ;
(2) Function declarations can be with or without parameters ;
(3) When declaring a function, the formal parameters are in parentheses , The default value of the formal parameter is undefined;
(4) When calling a function, the arguments in parentheses are ;
(5) Multiple parameters are separated by English commas ;
(6) When the number of real participating formal parameters does not match, the result is unpredictable , So try to match .
Four 、 Return value
function Function name ( Parameter list ) {
The body of the function ;
return sentence
}
Example :
<script>
function sub(a, b) {
return a - b;
}
var result = sub(3, 1);
console.log(result); //2
function fn(s) {
console.log(s);
return;
}
result = fn('hello'); //hello
result = fn(); // undefined
</script>
Be careful :
(1) When the function executes to return When the sentence is , Will end the function execution and return the specified value ;
(2) If the function does not return a value , There can be return sentence , but return It cannot be followed by other values ;
(3) If the function does not return sentence , The value returned is undefined.
5、 ... and 、 Internal properties of a function
5.1、arguments
stay JavaScript The function of arguments Property encapsulates the arguments of the function .
arguments explain :
(1)arguments Is a pseudo array object , It is not an array type , You can use instanceof Operator view ;
(2) When a function is called , The arguments passed are stored in arguments in ;
(3) It can be done by arguments Object's length Property to get the number of arguments ;
(4)arguments[0] Represents the first argument ,arguments[1] Represents the second argument , And so on ;
(5)arguments There is one of them. callee attribute , It is a function object , Point to the currently used function ;
(6) Only functions have arguments object , And each function has this built-in arguments.
Pseudo array description : Pseudo arrays are not really arrays
(1) Pseudo array Having an array lenght attribute ;
(2) Pseudo array It can be stored by index ;
(3) Pseudo array Some methods without real arrays pop()、push() etc. .
Example :
<script>
function add(a, b) {
// console.log(arguments);// It stores all the passed arguments
// console.log(typeof arguments);//object
// console.log(arguments instanceof Array); // false
// console.log(arguments instanceof Object);// true
// console.log(arguments.length);//8
// console.log(arguments[5]);//7
// Implement simple addition
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
// console.log(arguments[i]);
sum = sum + arguments[i];
}
console.log(sum);//44
}
add(2, 3, 4, 5, 6, 7, 8, 9);
</script>
5.2、this
<button> Button </button>
<script>
// this Point to the problem In general this Finally, it points to the object that calls it
// 1、 In global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window)
console.log(this); //window
function fn() {
console.log(this); //window
}
fn();
window.setTimeout(function() {
console.log(this); //window
}, 1000)
// 2、 Who calls... In method calls this Point to the who
var obj = {
say: function() {
console.log(this); //obj
}
}
obj.say();
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
console.log(this); //btn
})
// 3、 In the constructor this Point to an instance of a function
function Fun() {
console.log(this); //this Pointing to fun Instance object
}
var fun = new Fun();
</script>
Be careful :
(1) In global scope or ordinary function this Point to global object window( Pay attention to the... In the timer this Point to window);
(2) Who calls... In method calls this Point to the who ;
(3) In the constructor this Point to an instance of a function .
6、 ... and 、 Function method
6.1、call()
The name of the function .call();
Example :
<script>
window.color = 'red';
var obj = {
color: 'blue'
}
function show() {
console.log(this.color);
}
show(); // red
show.call(this); // red
show.call(window); // red
show.call(obj); // blue
function add(a, b) {
return a + b;
}
//console.log(window)
var result = add(2, 3);
console.log(result);
// adopt call() Method to call the function
result = add.call(this, 1, 8);
console.log(result); //9
result = add.call(window, 2, 5);
console.log(result); //7
result = add.call(add, 3, 4);
console.log(result); //7
</script>
Be careful : When using the function call() Method call , The first argument to the method is the function object , If there are parameters , From The second position starts with... In turn .
6.2、apply()
Function name .apply();
Example :
<script>
window.color = 'red';
var obj = {
color: 'blue'
}
function show() {
console.log(this.color);
}
show(); // red
show.apply(this); // red
show.apply(window); // red
show.apply(obj); // blue
console.log('------------------');
function add(a, b) {
return a + b;
}
var result = add(2, 3);
console.log(result);
result = add.apply(this, [1, 3]);
console.log(result);
result = add.apply(window, [4, 5]);
console.log(result);
result = add.apply(add, [4, 6]);
console.log(result);
console.log('----------------');
var color = 'green';
</script>
Be careful :
(1)apply() The application and call() There is no difference in method , You can change the reference image through the first parameter .
(2)apply() Method needs to encapsulate the arguments into an array and pass them uniformly . The first argument is the function object , The second parameter is the array , It encapsulates the parameters .
<script>
function print() {
'use strict'; // Specify strict mode
console.log(this);
console.log(this.color);
}
// print.call(null);
//print.apply(undefined);
</script>
Be careful :
(1) In strict mode , The function always points to the specified value ;
(2) In a non-strict mode , If you use call() perhaps apply() Method , Pass in null perhaps undefined Will be converted into a global window object .
6.3、call() and apply() Application
6.3.1、 Find the largest element in the array
<script>
var arr = [5, 20, 8, 51, 13];
// Find the largest element in the array
var maxVal = Math.max(arr);
console.log(maxVal); //NaN
var maxVal = Math.max(5, 20, 8, 51, 13);
console.log(maxVal); //51
maxVal = Math.max.apply(this, arr); //this=Math.max
console.log(maxVal); //51
maxVal = Math.max.apply(this, [5, 20, 8, 51, 13]); //this=Math.max
console.log(maxVal); //51
</script>
6.3.2、 Convert a pseudo - class array to a real array
<script>
function add() {
console.log(arguments); //Arguments(3)
console.log(arguments instanceof Array); //false
// Array.prototype Prototype slice Copy
var arr = Array.prototype.slice.apply(arguments);
console.log(arr); //Array(3)
console.log(arr instanceof Array); //ture
}
add(1, 2, 3);
</script>
6.3.3、 Array append
<script>
var arr = [];
Array.prototype.push.apply(arr, [1, 2, 3, 4, 5]);
console.log(arr);
Array.prototype.push.call(arr, 4, 5, 6);
console.log(arr);
</script>
6.3.4、 utilize call and apply Do inheritance
<script>
function Animal(name, age) {
this.name = name;
this.age = age;
this.show = function() {
console.log(this.name, this.age);
};
}
function Cat(name, age) {
// Inherit
Animal.call(this, name, age);
}
var cat = new Cat(' Persian cat ', 3);
cat.show(); // Persian cat , 3
function Dog(name, age) {
//Animal.apply(this, [name, age]);// Sure
Animal.apply(this, arguments);
}
var dog = new Dog(' Shapi dog ', 2);
dog.show();
</script>
6.4、bind()
<script>
function fun(y) {
console.log(this);
return this.x + y;
}
var obj = {
x: 2
}
//console.log(fun(3));
var fn = fun.bind(obj);//bind() Returns a new function fn
console.log(fn(4));
</script>
<script>
function getConf(color, size, other) {
console.log(color, size, other);
}
var fn = getConf.bind(null, '#ff0000', '500px');
fn('scrollTop');
fn('display')
</script>
7、 ... and 、 Immediate execution function
7.1、 Definition grammar
(function(){
The body of the function ;
})();
perhaps
(function(){
The body of the function ;
}());
<script>
function fn(a) {
console.log('hello ' + a);
}
fn('hi');
// Immediate execution function
(function(){
console.log('world')
})();
(function () {
console.log('hi')
}())
var r = (function (a, b) {
console.log(a, b);
return a + b;
})(1, 2);
console.log(r);
</script>
7.2、 Execute the function application immediately
<script>
// demand : Every time you call add, Both return plus 1 The number of ( The initial value is 0)
// 1. Use the previous method to realize
function add() {
return ++add.count; // to add The function object specifies a custom attribute count, For sharing data
}
add.count = 0;
console.log(add()); //1
console.log(add()); //2
console.log(add()); //3
// 2. Use immediate execution functions to implement
var rs = (function() {
var count = 0;
// A variable is declared in the immediate execution function
return function() {
return ++count;
};
})();
console.log(rs()); //1
console.log(rs()); //2
console.log(rs()); //3
</script>
2、 The following procedures exist , See what happened , How to solve
<script>
function fn() {
var arr = [];
for (var i = 0; i < 5; i++) {
arr[i] = function() {
return i;
}
}
return arr;
}
var f = fn();
console.log(f);
console.log(f[0]());
console.log(f[1]());
</script>
Use execute now function
<script>
function fun() {
var arr = [];
for (var i = 0; i < 5; i++) {
(function(n) {
arr[n] = function() {
return n;
}
})(i);
}
return arr;
}
f = fun();
console.log(f);
console.log(f[0]());
console.log(f[1]());
console.log(f[4]());
</script>
边栏推荐
- Huitongda officially landed at the Hong Kong Stock Exchange: the gross profit margin continued to decline, and the book value of several shareholders still suffered losses
- Application service access configuration parameters
- next_ Permutation full permutation function
- (Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
- Architecture decryption from distributed to microservice: several common microservice architecture schemes
- Navigator object
- 微服务系统设计——接口文档管理设计
- Mcu-08 interrupt system and external interrupt application
- Leetcode skimming questions - the 72nd biweekly match and 281 weekly match
- 微服务系统设计——子服务项目构建
猜你喜欢
Vite+web3:报错出现ReferenceError: process is not defined
Digital transformation informatization data planning and technology planning
Ten excellent business process automation tools for small businesses
An analysis of the comments on the TV series Douban by procedural apes
[untitled]
Number of occurrences of numbers in the array (medium difficulty)
Recommend 14 commonly used test development tools
High quality defect analysis: let yourself write fewer bugs
[North Asia data recovery]_ mdb_ catalog. Mongodb database data recovery case in case of WT file corruption
On software requirement analysis
随机推荐
Uniapp wechat applet calls mobile map to navigate to the target point
中电投先融期货这家公司怎么样?期货开户办理安全吗?
Ten excellent business process automation tools for small businesses
Business based precipitation component = & gt; manage-table
Leetcode topic [array] -216- combined sum III
About whether arm's large and small end mode is related to CPU or compiler
Two micro service interviews where small companies suffer losses
Continue to help enterprises' digital transformation -tce has obtained the certification of the first batch of digital trusted service platforms in China
Optimizing bloom filter: challenges, solutions, and comparisons
[JS Framework] Failed to execute the callback function:
Complete Guide to web application penetration testing
How about China Power Investment Xianrong futures? Is it safe to open futures accounts?
Online sequence flow chart making tool
JS string method
Application service access configuration parameters
如何在 R 中使用 Fisher 的最小显着性差异 (LSD)
It is often blocked by R & D and operation? You need to master the 8 steps before realizing the requirements
Palindrome string (two methods)
Leetcode daily question solution: 717 1-bit and 2-bit characters - reverse order
TCE was shortlisted as a typical solution for ICT innovation of the Ministry of industry and information technology in 2020