Take you to learn the advanced function of JavaScript (2)

Tell me Zhan to hide 2020-11-06 20:37:31
learn advanced function javascript


Last article shared 《 Take you to study Javascript Advanced function in the ( One )》, Continue today javascript The content of advanced function of .


1 Strict mode

1.1 What is the strict pattern

JavaScript In addition to providing normal mode , It also provides a rigorous model (strict mode).ES5 The strict model is to adopt a restrictive Javascript A way of variation . I.e. operate under strict conditions js Code .
The strict pattern is in IE10 Only in the above version of the browser will be supported , Older browsers will be ignored .
Strict mode for normal javascript Some semantic changes have been made :

  1. Eliminated Javascrip Some unreasonable grammar 、 Not rigorous , Reduced some weird behavior .
  2. Eliminates some of the unsafe aspects of code running , Ensure the safety of code operation .
  3. Improve compiler efficiency , Increase running speed .
  4. Disabled in ECMAScript Some of the syntax that may be defined in future versions of , For future new versions of Javascript Pave the way . Than

Such as some reserved words :class,enum,export,extends,import,super You can't make variables .

1.2 Turn on strict mode

Strict patterns can be applied to entire scripts or individual functions . So in use , We can divide strict mode into script on strict mode and
Turn on strict mode for the function in two cases

  1. Turn on strict mode for the entire script

Turn on strict mode for the entire footstep file , You need to make a specific statement before all statements "use strict"

<scirpt>
"use strict"
console.log(" This is the most rigorous model ")
</scirpt>
  1. Turn on strict mode for functions

To turn on strict mode for a function , Need to put "use strict";( or ’use strict’) The declaration is placed before all statements in the body of the function .

<script>
function fn() {

'use strict' // The following code follows a strict pattern 
}
</script>

3.3 Changes in strict patterns

The strict pattern is right javascript The language of
Law and action , There have been some changes

  1. Variables specify
  • In normal mode , If a variable is not declared, it is assigned a value , The default is global variables .
  • var A statement of order , And then use
<script>
‘use strict’
num = 10
console.log(num)
</script>

The effect is as follows
image.png
It is strictly forbidden to delete declared variables .

  1. In strict mode this Point to the problem
  • Previously in global scope functions this Point to window object .
  • In strict mode, in the global scope of the function this things undefined.
  • Before the constructor without new You can also call , When a normal function ,this Point to global object .
  • In strict mode , If the constructor does not add new call ,this Will report a mistake . new The instantiated constructor points to the created object instance .
  • In strict mode , In the timer this Point to or window.
  • In strict mode , event 、 The object still points to the caller .
  1. Function change
  • In strict mode, functions cannot have duplicate parameters
  • Functions must be declared at the top level , The new version of the js Will introduce “ Block level scope ”(ES6 Has introduced ). In order to be in line with the new version , Functions are not allowed to be declared within blocks of code that are not functions , If in if,for Statement to declare a function .

2 Higher order function

Higher order functions are functions that operate on other functions , It takes a function as a parameter or a function as a return value .

function fn(callback) {

callback && callback()
}
fn(function(){

alert('lanfeng')
})
function fn() {

return function() {

}
}
fn()

here fn It's a higher-order function
Function is also a data type , It can also be used as a parameter , Pass to another parameter to use , The most typical is as a callback function

3 Closure

3.1 Variable scope

Variables are divided into two types according to their scopes : Global and local variables .

  1. Global variables can be used inside functions
  2. Local variables cannot be used outside a function
  3. When the function is finished , Local variables in this scope will be destroyed .

3.2 What is a closure

A closure is a function that has access to a variable in the scope of another function . in other words , A scope can access local variables inside another function .

//fn External scopes can access fn Internal local variables 
function fn() {

var num = 10
function fun () {

console.log(num) // You can visit num
}
return fun
}
var f = fn()
f() //10
//fn External scopes can access fn Internal local variables 
function fn() {

var num = 10
// Returns an anonymous function 
return function() {

console.log(num) // You can visit num
}
}
var f = fn()
f() //10

The main function of closures is : It extends the scope of variables

3.3 Closure cases

  1. Cycle registration click events
//html
<ul class="nav">
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
//js
// Click on li Output current li The index of 
// Using dynamic track and field attributes 
var lis = document.querySelector('.nav').querySelectorAll('li')
for(var i=0 ;i<lis.length; i++) {

lis.index = i
lis[i].onclick = function() {

console.log(this.index)
}
}
// Using closures 
var lis = document.querySelector('.nav').querySelectorAll('li')
for(var i=0 ;i<lis.length; i++) {

(function(i) {

lis[i].onclick = function() {

console.log(i)
}
})(i)
}
  1. In the loop setTimeout()
//html
<ul class="nav">
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
//js
// Use closures 
var lis = document.querySelector('.nav').querySelectorAll('li')
for(var i=0 ;i<lis.length; i++) {

(function(i){

setTimeout(function() {

console.log(lis[i].innerHTML)
},3000)
})(i)
}
  1. Calculate the taxi price
var car =function() {

var start = 13;
var total = 0;
return {

// Normal price 
price: function(n) {

if(n <= 3) {

total = start
} else {

total = start + (n-3)* 5
}
return total;
},
// After the congestion 
yd: function(flag) {

flag? total+ 10 :total
}
}
}()
console.log(car.price(5))
console.log(car.yd(true))

3.4 Closure summary

  1. What is a closure ?

Closure is a function ( One scope can access the local variables of another function )

  1. What do closures do ?

Extend the scope of the variable

4 recursive

4.1 What is recursion

If a function can call itself internally , So this function is recursive .
Recursive functions work just as well as loops
Because recursion is easy to happen “ Stack overflow ”(stack overflow), So you have to add exit conditions return

4.2 Using recursion to solve mathematical problems

  1. seek 123…*n
function fn(n) {

if(n = 1) {

return 1
}
return n * fn(n-1)
}
console.log(fn(3)) // 6

4.3 Use recursion to find : according to id Return the corresponding data object

var data = [{

id:1,
name:' Home appliance ',
goods: [
{

id: 11,
gname: ' The refrigerator '
},
{

id: 12,
gname: ' Washing machine '
}
]
},
{

id: 2,
name: ' dress '
}
]
function getObj(arr, id) {

var o = {
}
arr.forEach(function(item){

if(item.id === id) {

o= item
} else if(item.goods && item.goods.length>0) {

o =getObj(item.goods, id);
}
})
return o
}
console.log(getObj(data, 1))

5 recursive

5.1 Shallow copy and deep copy

  1. Shallow copy is just a layer of copy , Deeper object level copy only references .
  2. Deep copy copy copy multilayer , Every level of data is copied .
  3. Object.assign(target, …sources) es6 New method can be shallow copy
var obj = {

id: 1,
name: 'andy',
msg: {

age: 18
}
}
var o = {
}
for(var k in obj) {

// k It's the property name 
o[k] = obj[k]
}
console.log(o)
o.msg.age = 20
console.log(obj) //obj change 
// use es6 Grammatical sugar 
Object.assign(o, obj)

image.png

// Deep copy , Using recursion 
function deepCopy(newObj, oldObj) {

for(var k in oldObj) {

// Determine what type of attribute value we have 
var item = oldObj[k]
// Determine if it's an array 
if(item instanceof Array) {

newObj[k] = []
deepCopy(newObj[k], item)
} else if(item instanceof Object) {

// Judge whether it is the object 
newObj[k] = {
}
deepCopy(newObj[k], item)
} else {
 // It's a simple data type 
newObj[k] = item
}
}
}
deepCopy(o,obj)
console.log(o)

summary

This article mainly shares the strict pattern of functions 、 Higher order function 、 Closure 、 recursive 、 Deep copy 、 The usage and application of knowledge points such as shallow copy .

版权声明
本文为[Tell me Zhan to hide]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云