About those things about JS ES5, the content is recommended for collection in detail

Things about JS ES5

The full text is 7,500 words in total, 6,000 words are removed from the code, and the reading is expected to take 20 minutes. It may take a day or two to understand.

ES5 New Syntax – Produced in 2009

Strict mode : JS provides more error reporting to assist programmers to write healthier code

  • Opening method, write at the beginning of the script: 'use strict'
  • specific function
    • Variables must be declared first
    • Functions must be declared before they are used
    • The this keyword in the function: if it is window, change it to undefined
  • Precise configuration of object writing – tasteless for rookies, artifact for masters
    • objecttigondedefinePrroperty
    • whether writable is reassignable
    • enumerable: whether it can be traversed
    • configurable : whether it can be reconfigured
    • value: value
    • get: computed property - use without() to trigger
    • set: listener
  • The way to protect the object
    • prexxxx: prevent extension, prevent adding new writing
    • seal: prevent adding and deleting attributes
    • freeze: prevent addition, deletion and modification

ES6 new features

  • Produced in June 2015, it is a milestone of JS
  • New Scope: Variables must be declared with let and const
    • Corresponds to the window global scope, used to store custom attributes
    • Before ES6: You must first write a dawn function self-call – to provide local scope
    • Block-level scope: use {} accessories, let and const
    • Corresponding to the function scope, the replaced Dawn function scope can provide private variables for the function
  • let and const
    • let: the amount of change, the declared variable can be reassigned later
    • const: constant, must be assigned when declared, and cannot be reassigned later
    • About statement promotion
    • There is a statement promotion, temporary storage dead zone : temporary promotion , stored in a temporary storage dead zone , cannot be used, must be executed to the line where let / const the code is located before it can be used

The author's intention : In order to be compatible with the previous code that relies on declaration promotion, the author dare not delete the declaration promotion feature, and uses error reporting to force users to declare variables first, and then use variables; if variables are used first, an error will be reported-template string-converted to
html
code Born of splicing
- supports the replacement of partial content of strings - ${}
- supports newline operations

scope

what is it Everything is an object. The scope of the object
before es6 has two scopes: global scope and local scope global global scope: the API provided by the system is stored in the object for operating the host environment特殊功能

Host function: The relationship between the parasite and the array is here the relationship between the browser, node and js

If nodejs is the host, then the global object is globalThis
makes Hugo the browser's global object is window

local local scope: 被调用后The temporarily generated object of the function is used to store the variables declared in the function.
It is static before it is called

Scope chain: When there is a scenario of multiple scope nesting - functions nested within functions

When the inner function uses a variable, it will follow the principle of proximity, and use the nearest variable when searching from the long scope

Declarative hoisting: JS unique design – very rubbish

It will cause the effect of the written code to be different from the original one.
Declaration operation:
The life operation will be limitedly read by the js editor and promoted to the top of where it is used, and then execute the code with the adjusted order; it is often considered— hoisting of functions takes precedence over var

function : overall promotion – function name ++ function body
var promotion statement does not promote assignment

Closure: When there is a b function in the ah function, the b variable is used in the wave function

function a(){
    
    
        var c=11
        function b(){
    
    
          console.log(c);
        }
        // 由于函数作用域时临时的调用结束后会自动销毁,所以
        // b函数为了保证自己能顺利执行,所以会把外部作用与保存在兹省的scopes属性里
        // 这个被保存在scopes中的函数作用域-- 称呼闭包
      }

Required use: making private properties for functions

var 函数 =(function(){
    
    
        var 变量=return function(){
    
    

        }
      })()

Disadvantages of closures:

The scope of the function is temporary, and will be destroyed after running to save memory. If
the closure is closed, half of the tree scope will be saved, so it will waste memory.

arguments: function

arguments: an implicit variable in the function; it saves all the parameters received when the function is called

Uses: Often used to implement functions whose number of actual parameters is not fixed

Function overloading:
use if to judge with the arguments variable, judge that the number and type of actual parameters are different, and reload different logic processing

Accessor syntax:
object. Attribute name: dot syntax
object [js]: square bracket syntax--because the attribute name is js code, it is more flexible

object is an imported type

The memory is divided into heap memory and stack memory .
Stack memory : fast query speed, storing small data, storing basic data types + object addresses are equivalent to address directories.
Heap memory: storing large data - object types have address memory

object shallow copy

Restricted to make an empty object, traverse the original object and copy the attributes in it to the new object one by one.
Applicable type: if it is an object type, use深拷贝

The function this is used with the object

Due to the existence of this, the parameter passing of the function has changed.
Solution 1-traditional: the function accepts the actual parameter of the object through formal parameters, and then processes the function.
Solution 2-new style: put the function in the object, and the this keyword represents the 工作时location of object

Constructor

It is a function, singular because of the special work - the function 创建构造函数of the object
Naming convention: generally use big hump to distinguish
Step
1. Create an empty object
2. Store the received actual parameters into the above empty object

prototype concept

Purpose: To save memory, avoid generating the same function every time an object is created
Realization: The constructor has a prototype, which can store shared functions
When generating objects, let the __proto__ attribute, link, and constructor prototype
object The prototype connection mechanism: when using a property of the object, if the object does not have it, it will automatically go to

The new operator __proto__ looks for

new operator

When the new element character is placed before the function, the function will automatically complete four lines of code

var this
this = {
    
    }
this.__proto__ =函数.prototype
return this

The new this points to

Function (): no prefix is ​​the window object. Function
(): object – the object where the runtime is What happens to the variables of ? Start the scope chain mechanism: look up this running example in the upper scope. We found that what is printed out is window (if you don’t have it, look up) then what is the function in the function? look at the code below





insert image description here

insert image description here

var emp ={
    
    
  ename:'qiushan',
  show(){
    
    
    const b=()=>{
    
    
      console.log('this:',this);
    }
    b()
  },
  
}
emp.show()
// show 函数中的this是其前方的emp

insert image description here

Higher-order functions for arrays

Higher-order functions: when other functions are used in the function, they are called higher-order functions.
ES6 adds more methods to the array type.
You can view these methods by printing the prototype of the array.

console.log(Array.prototype)

Due to the popularity of front-end and back-end projects, the demand for using JS to process webpage data on the front-end has increased sharply
Front-end and back-end separation routine: use Ajax to request data from the server, temporarily splicing it into HTML code on the front-end (browser), and finally display //
every The browsers of each user are spliced ​​separately – share the pressure on the server.
The front and back ends are not separated: the back end directly splices the data into HTML, and sends a browser to display
//The server is under heavy pressure, and splicing is required--big websites can't handle it

The data sent by the server is usually an array – it is checked from the database,
so the front-end JS is required to improve the processing ability of the array

Determine whether the data in the following array is greater than 0

<script>
  // 高阶函数:函数中使用了其他函数,就叫高阶函数
  console.log(Array.prototype);
  var nums = [12, 13, 14, 15, 16, -1, 18];
  // 判断配个元素都大于0
  var a = nums.every((value, index, array) => {
      
      
    return value > 0;
  });
  console.log('a:',a);
</script>

When one of them is negative,
insert image description here
otherwise it is true.
insert image description here
The elements in nums are detected by the arrow function in turn. Each element must provide three values: value, and the serial number comes from the array. The arrow
function needs to judge whether the element meets the conditions
.
code:

<script>
  // 高阶函数:函数中使用了其他函数,就叫高阶函数
  console.log(Array.prototype);
  var nums = [12, 13, 14, -15, 16, -1, 18];
  // 判断配个元素都大于0
  var a = nums.every((value, index, array) => {
      
      
    console.log(value,index,array);
    return value > 0;
  });
  console.log('a:',a);
</script>

Run the code:
insert image description here
We found that the code execution will be interrupted when there is a negative number.
In fact, the parameter every is equivalent to returning a value as long as one of the requirements is not met, and ending the operation.

Simplify function

// 1,没有使用的形参可以不写
a = nums.every((value) => {
    
    
  console.log(value);
  return value < 0;
});
// 3,箭头函数形参只有一个省略()
a = nums.every((value) => {
    
    
  console.log(value);
  return value < 0;
});
// 4,箭头函数的函数体只有一行省略return
a = nums.every((value) => {
    
    
  value < 0;
});

Exercise: Determine whether the following arrays are even

var nums=[12,5,32,1231,1223,-1,123,43]

Realize the effect:
insert image description here

Exercise: Determine whether the following arrays are negative

var nums=[12,5,32,1231,1223,-1,123,43]

Realize the effect:
insert image description here

Higher order function some

some: Some, there are some that meet the conditions,
as long as there is true, – similar to logical or, and true is true

Like the following: determine whether there are items greater than 500

// 高阶函数some
// some:一些,有一些满足条件的
// 只要有真的就行,--类似于逻辑或,又真则真
var nums=[12,564,123,1231,5346,68456]
var mians=nums.some(value=>value>=500)
console.log(mians ? '有' : '没有');

result:
insert image description here

filter filter

Find all people whose salary is greater than 30 and whose salary is less than 10000

map mapping

Map data to HTML code
insert image description here

**map: **Automatic convenient array, each element is processed with an arrow function and the return value forms a new array

join: By default, strings are separated by commas, and parameters can be passed by passing parameters.
Effect
insert image description here
Exercise: Map the data in the following array to the web page

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <ul id="cart">

    </ul>
    <script>
      var cars=['冬瓜','南瓜','西瓜','美离间','奇异果','西红柿','桃子']
      // 把元素放到li标签里面
    </script>
  </body>

  </html>
</body>
</html>

Answer:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <ul id="cart">

    </ul>
    <script>
      var cars=['冬瓜','南瓜','西瓜','美离间','奇异果','西红柿','桃子']
      // 把元素放到li标签里面
      var car=cars.map((value)=>{
      
      
        return `<li>${ 
        value}</li>`
      })
      var a=car.join('<br/>')
      console.log(a);
      cart.innerHTML =a
    </script>
  </body>

  </html>
</body>
</html>

For example, we can also spend a little time to play

<body>
    <ul id="list">
      <!-- 占位 -->
    </ul>
    <script>
      var stus=[
        {
      
      name:"宝宝",age:"22",color:"red"},
        {
      
      name:"山海",age:"42",color:"blue"},
        {
      
      name:"秋慧",age:"21",color:"yellow"},
        {
      
      name:"玛丽",age:"62",color:"red"},
        {
      
      name:"凯瑞",age:"82",color:"red"},
        {
      
      name:"小李",age:"21",color:"red"},
        {
      
      name:"丘丘人",age:"20",color:"skyblue"},
      ]
      var strs=stus.map((value)=>{
      
      
        return `<li style="background-color:${ 
        value.color}">${ 
        value.name}-${ 
        value.age}</li>`
      })
      str=strs.join("<br />")
      list.innerHTML=str
    </script>
  </body>

forEach

reduce

reduce donation method 1
insert image description here
method 2
insert image description here
insert image description here

About ES6

Some new features of ES6

  • arrow function

    • Simpler way of writing anonymous functions
    • ()=>{ } 》》》 function(){ }
    • Two syntax sugars are provided
      • When there is only one formal parameter, parentheses can be omitted –x=>{ }
      • {return} can be omitted when the function body has only one line
    • this-oriented
      • function(): window
      • 严格模式下时undefind
      • object.function(): object
      • new function (): the constructed object
      • Arrow function (): itself is not searched according to the scope chain
  • Higher-order functions for arrays

    • function uses other functions
  • every: every element meets the requirements

  • some: filter out the elements that meet the conditions

  • filter: filter out the elements that meet the conditions

  • map: map - map the main clause to HTML

    • Usually used with the join attribute
  • forEach: traverse the array

  • forEach is suitable for those with this method in the prototype

    • for...of: suitable for element/array-like
  • reduce: merge

Not detailed enough? Of course, this is mainly about ES5. It is recommended to read this article about ES5+ES6.
Doesn’t JavaScript? Take you to get started with JavaScript ES5-ES6 in 25 minutes

Guess you like

Origin blog.csdn.net/weixin_50112395/article/details/126094038