当前位置:网站首页>Function advanced application
Function advanced application
2022-07-18 06:17:00 【zzzlln】
One 、 How to define a function
(1)、 Function declaration
function fn(){
console.log('this is a function')
}
(2)、 Function expression
var fn = function(){
console.log(' Assignment expression function ')
}
(3)、 The form of built-in constructor
var fn3 = new Function("num1", "num2", "return num1+num2");
console.log(fn3(2, 3));
recommend Use the second form , The third kind uses relatively little , But it is also the content that must be mastered .
Two 、 Function call method
2. Function call method
(1)、 Function name ()
var fn1 = function () {
console.log(" Function name ()");
}
window.fn1();
fn1();
(2)、 Self calling
var fn2 = (function () {
console.log(" Self calling ");
})();
(3)、call() call
fn1.call();
(4)、 Object
var obj1 = {
name: " Xiaogang ",
say: function () {
console.log(this.name + " I like spicy strips !")
}
}
obj1.say();
(5)、 Function calls in the array
var arr = [
100,
" ha-ha ",
function () {
console.log(this);
console.log(this[1] + " I am the element in the array , Is also a function ");
},
function () {
console.log("66666");
},
true
];
console.log(arr[2]);
arr[2]();//
arr[3]();
(6)、 Function as a parameter
function fn3(x) {
x();
}
fn3(function () { console.log(" I'm a function and a parameter "); });
(7)、 Function as the return value
function fn4() {
return function () { console.log(" I am a function and return value !") }
}
fn4()();
3、 ... and 、 Closure
(1) Definition
Closure is Functions that can read internal variables of other functions , Because in Javascript In language , Only subfunctions inside a function can read local variables , therefore A closure can be simply understood as “ A function defined inside a function ”. therefore , stay The essence On , A closure is a bridge connecting the inside and outside of a function .
Closure purpose :
You can read the internal members of a function outside the function
Keep members of a function alive in memory all the time
principle
In fact, js In the scope mechanism of , There is a scope that is eternal , Namely window Global scope , As long as the browser window doesn't close , The global scope will not be destroyed , This windows The global scope is eternal , Define a function in the global scope , No matter how many times you call , These calls can share the same global variable .
However Local scope Is not! , It only works when the function is called , When the function call is complete , The local scope is closed , That means that the local variable is invalid . So we can't get local variables under the global scope , No more local variables can be obtained under other scopes .
But closures are different , You can make the scope of its parent function permanent , image windows Global scope , Always in memory . This is also the essence of closures . It's also what we talked about closure The second function locks local variables . When the closure function is called , It will dynamically open up its own scope , Above it is the eternal scope of the parent function , Above the scope of the parent function , yes window Eternal global scope . The closure function is called , Its own scope is closed , Disappeared from memory , But the eternal scope of the parent function and window The eternal scope is still in the memory is open . When the closure function is called again , You can also access these two scopes , It may also save the data generated when it was last called . Only when the reference of the closure function is released , Its parent scope will finally close ( Of course The parent function may have created multiple closure functions , You need to release all the closure functions , The scope of the parent function will be closed ).
The internal variable of the access function of the closure
Some examples of closures
Case a :
var name = "this window";
var obj1 = {
name: "this object",
getName: function () {
var name = "this func1";
console.log(this.name);;//this object
console.log(name);//this window
return function () {
// Closure function
// var name = "this func2";
console.log(name);//this func1
console.log(this.name);//this window
}
console.log(this.name);
console.log(name);
}
}
obj1.getName()()
Case 2 :
function getRandom(min, max) {
var num = Math.floor(Math.random() * (max - min) + min);
console.log("num:" + num)
// Closure
return function () {
console.log(num);
}
}
var result = getRandom(1, 10);
result();
result();
(4)、 Lock variables of closure
Some examples of closures
// 1、 random number
/* function getRandom(min, max) {
var num = Math.floor(Math.random() * (max - min) + min);
console.log(num);
}
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20);
getRandom(10, 20); */
function getRandom(min, max) {
var num = Math.floor(Math.random() * (max - min) + min);
return function () {
console.log(num);
}
}
var result = getRandom(10, 20);
// console.log(result);
result();
result();
result();
result();
result();
result();
result();
result();
/* getRandom(10, 20)();
getRandom(10, 20)();
getRandom(10, 20)();
getRandom(10, 20)();
getRandom(10, 20)();
getRandom(10, 20)(); */
(5)、 Closure case 1
Some examples of closures
<script>
// 1
/* function fn() {
var name = "hello";
return function () {
return name;
}
}
var fnc = fn();
console.log(fnc()); */
// 2
/* var inner = "hi";
function fn() {
var inner = "hello";
inner = function () {
return inner;
}
console.log(inner());
}
fn(); */
//3
/* function fn() {
var name = "hello";
return function callback() {
return name;
}
}
var fn1 = fn();
function fn2(f) {
console.log(f());
}
fn2(fn1); */
//4
/* (function () {
var name = "hello";
var fn1 = function () {
return name;
}
fn2(fn1);
})()
function fn2(f) {
console.log(f());
} */
// console.log(name);
//5
/* function fn() {
var name = 'hello'
setName = function (n) {
name = n;
}
getName = function () {
return name;
}
return {
setName: setName,
getName: getName
}
}
var fn1 = fn();
console.log(fn1.getName());
fn1.setName('world');
console.log(fn1.getName()); */
// 6
/* var fn = (function () {
var arr = [];
console.log(1);
return function (val) {
if (arr.indexOf(val) == -1) {
// There is no val To perform
arr.push(val);
console.log(' The function is executed ', arr);
} else {
console.log(' This time the function doesn't need to be executed ');
}
console.log(' Print after the function call , Easy to view cached arrays :', arr);
}
})();
fn(10);
fn(10);
fn(1000);
fn(200);
fn(1000); */
// 7
var arr = [];
for (var i = 0; i < 3; i++) {
// console.log(i);
arr[i] = (function (i) {
console.log(i);//2
return function () {
console.log(i);
}
})(i);
// console.log(i);
}
arr[0]();
arr[1]();
arr[2]();
/*
This example is a typical application of closure function , In the example, only two functions are nested , But add window Global scope ,
There are three nested scopes . among for Three times , Anonymous self executing function is called three times , Just open three function scopes ,
Saved when opening the first scope i The value of is 0, The second scope saves 1, The third one is 2.
Call the parent function three times , Three more closure functions are created , Each closure function is accessed up its own scope chain , The values accessed are all different .
Three closure functions are called , Their own scope is closed ,
But the respective parent function scopes are still open in memory , The next time the closure function is called , Then access its own scope .
As in the window The global scope defines a function , Function call several times , The global scope is , Each call then accesses the global scope .
*/
</script>
- 、 Closure case II
Some examples of closures

4. Function recursion
Recursive execution model

5. Fibonacci sequence
Fibonacci number , It refers to such a sequence :1、1、2、3、5、8、13、21、…… In Mathematics , The Fibonacci sequence is defined recursively as follows :F0=0,F1=1,Fn=Fn-1+Fn-2(n>=2,n∈N*), In words , It's Fibonacci sequence 0 and 1 Start , Then the coefficients of the Fibonacci series are added by the previous two numbers .
The commonly used methods for calculating Fibonacci sequence are divided into two categories : Recursion and loops .
(1)、 recursive
Method 1 : Normal recursion
Beautiful code and clear logic . But there is the problem of double counting , Such as : When n by 5 Calculate when fibonacci(4) + fibonacci(3), When n by 4 To calculate fibonacci(3) + fibonacci(2) , At this time fibonacci(3) It's double counting . function fibonacci(50) There will be browser fake death , After all, recursion requires a stack , The number is too large and there is not enough memory .
function fibonacci(n) {
if (n == 1 || n == 2) {
return 1
};return fibonacci(n - 2) + fibonacci(n - 1);
}fibonacci(30)Method 2 : Improved recursion - Make the first two digits into parameters to avoid double calculation
function fibonacci(n) {
function fib(n, v1, v2) {
if (n == 1)
return v1;
if (n == 2)
return v2;
elsereturn fib(n - 1, v2, v1 + v2)
}return fib(n, 1, 1)
}fibonacci(30)Method 3 : Improved recursion - Use the closure feature to store the operation results in an array , Avoid double counting
var fibonacci = function () {
let memo = [0, 1];let fib = function (n) {
if (memo[n] == undefined) {
memo[n] = fib(n - 2) + fib(n - 1) }return memo[n]
}return fib;
}()fibonacci(30)Method four : Improved recursion - Pick out the function function that stores the calculation results
var memoizer = function (func) {
let memo = [];return function (n) {
if (memo[n] == undefined) {
memo[n] = func(n) }return memo[n]
}};var fibonacci=memoizer(function(n){
if (n == 1 || n == 2) {
return 1
};return fibonacci(n - 2) + fibonacci(n - 1);
})fibonacci(30)(2)、 loop
Method 1 : Ordinary for loop
function fibonacci(n) {
var n1 = 1, n2 = 1, sum;
for (let i = 2; i < n; i++) {
sum = n1 + n2 n1 = n2 n2 = sum }return sum
}fibonacci(30)Method 2 :for loop + Deconstruct assignment
var fibonacci = function (n) {
let n1 = 1; n2 = 1;for (let i = 2; i < n; i++) {
[n1, n2] = [n2, n1 + n2] }return n2
}fibonacci(30)The running time of various methods is shown in the figure below : Normal recursion > Improved recursion >for loop

边栏推荐
- @Use of equalsandhashcode annotation
- Experience first! What kind of experience is it to write fluent in the browser?
- How does win11 set the multitask window? Win11 method of setting multi task window
- QT UI Designer interface common operation records (qtablewidget)
- 【golang】基于go语言的堆结构模板
- 现在网上开户安全么?想知道券商选哪个比较好尼?本人小白不懂
- The data transmission mode and online monitoring management system of multi-channel vibrating wire wireless acquisition instrument for engineering monitoring instruments
- Where can I find the computer network speed detection
- [MySQL learning notes 33] log
- Foundation of deep learning: 9 Reproduce classic networks: lenet5 and alexnet
猜你喜欢

Foundation of deep learning: 9 Reproduce classic networks: lenet5 and alexnet

如何将notepad++设置为默认打开方式

What's the use of games| Game application value research case collection

Neusoft Ruichi has reached a strategic cooperation with United electronics to seize a new outlet in the domestic basic software market

Six capabilities of test and development

【森城市】GIS数据漫谈(四)— 坐标系统

阿里内网疯传的P8“顶级”分布式架构手册被我拿到了

Scan code login function of IM instant messaging software development

Intensive reading of the paper: deep reinforcement learning and intelligent transportation (I)

Beihang & Institute of Information Technology & meituan proposed lbdt, which is based on spatiotemporal interaction of language bridging to accurately segment directional video objects, with performan
随机推荐
MYSQL建表语句错误:1103-Incorrect table name
在线问题反馈模块实战(二):封装代码自动生成类文件器
共话机器翻译新风向,第二届小牛翻译论坛启幕在即
ECCV 2022 | multi domain long tail distributed learning, research on unbalanced domain generalization (open source)
什么是真正的HTAP?(一)背景篇
3D reconstruction line structured light (1)
Notes on linear algebra 2
面对对象
正则表达式
蓝桥杯2022年第十三届省赛第三题-求和 (前缀和 或 公式法)
Loj#510-「LibreOJ NOI Round #1」北校门外的回忆【线段树】
杰理之开启按键配对,第一次配对 tws 后,再进行交叉配对很难配对 成功【篇】
MySQL数据库在触发器中定义游标
Loj#576-「LibreOJ NOI Round #2」签到游戏【线段树】
Use excel2016's functions to generate random 16, 32, and 36 bit ID string contents
函数与Symbol
Is it safe for qiniu securities to open an account? Is it reliable?
郑州大学数据库课设资源说明
Notes on Linear Algebra 1
Sword finger offer punch stack queue heap