Function Advancements with javascript

1 Strict mode

1.1 What is a strict mode

In addition to providing normal mode, JavaScript also provides strict mode.The strict pattern of ES5 is one way to adopt restrictive Javascript variants.That is, js code is run under strict conditions.
Strict mode is only supported in browsers over IE10, and older browsers are ignored.
Strict mode makes some changes to normal javascript semantics:

  1. Eliminates some unreasonable, inaccurate Javascrip syntax and reduces some bizarre behavior.
  2. Eliminates some unsafe aspects of code running to ensure the security of code running.
  3. Increase compiler efficiency and speed.
  4. Disables some syntax that may be defined in future versions of ECMAScript to pave the way for future versions of Javascript.than

For example, some reserved words: class,enum,export,extends,import,super cannot be variables.

1.2 Turn on strict mode

Strict patterns can be applied to the entire script or to individual functions.Therefore, when using the strict mode, we can divide it into script open strict mode and script open strict mode.
Two cases of turning on strict mode for a function

  1. Turn on strict mode for the entire script

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

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

To turn strict mode on for a function, you need to precede all statements in the body with "use strict"; (or "use strict") declarations.

<script>
    function fn() {
        'use strict' //The following code follows a strict pattern
    } 
 </script>

3.3 Changes in Strict Mode

Strict mode for javascript language
Law and behavior have changed

  1. Variable specification
  • In normal mode, if a variable is assigned without a declaration, the default event global variable.
  • var command declaration, then use
<script>
  'use strict'
    num = 10
    console.log(num)
 </script>

The effect is as follows

Deleting declared variables is strictly prohibited.

  1. this pointing problem in strict mode
  • this previously pointed to a window object in a global scope function.
  • this event undefined in a function in global scope in strict mode.
  • Previous constructors can be called without new, and this points to global objects when common functions are used.
  • In strict mode, this will error if the constructor is not called with a new call.The constructor of the new instantiation points to the object instance created.
  • In strict mode, does this point to window in the timer?
  • In strict mode, the event, object, or point to the caller.
  1. Functional variation
  • Functions cannot have parameters with duplicate names in strict mode
  • Functions must be declared at the top level, and new versions of js introduce "block-level scopes" (introduced in ES6).Declaring functions within code blocks that are not functions, such as in if, for statements, is not allowed in order to keep up with the new version.

    2 higher order functions

    A higher-order function is a function that operates on other functions and receives functions as parameters or functions as return values.

function fn(callback) {
    callback && callback()
}
fn(function(){
    alert('lanfeng')
})
function fn() {
    return function() {
  }
}
fn()

fn is now a higher-order function
Functions are also a data type that can be passed as parameters to another parameter, most typically as callback functions

3 Closure

3.1 Variable Scope

Variables are divided into two types according to scope: global and local.

  1. Global variables can be used inside a function
  2. Local variables cannot be used outside a function
  3. When the function is executed, local variables in this scope are destroyed.

    3.2 What is a closure

    A closure is a function that has access to a variable in the scope of another function.That is, one scope can access local variables within another function.

//Scopes outside fn can access local variables inside fn
function fn() {
    var num = 10
  function fun () {
    console.log(num) //Accessible num
  }
  return fun
}
var f = fn()
f() //10
//Scopes outside fn can access local variables inside fn
function fn() {
    var num = 10
  
  // Returns an anonymous function
  return function() { 
    console.log(num) //Accessible num
  }
}
var f = fn()
f() //10

The primary role of closures: extends the scope of variables

3.3 Closure Cases

  1. Circular Register Click Event
//html
<ul class="nav">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>
//js
//Click li to output the index of the current li
//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)
  }
}
//How closures are utilized
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. setTimeout() in a loop
//html
<ul class="nav">
  <li>a</li>
  <li>b</li>
  <li>c</li>
  <li>d</li>
</ul>
//js
//Utilize Closure
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 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 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?

A closure is a function (a local variable whose scope can access another function)

  1. What does a closure do?(

Extend the scope of a variable

4 Recursion

4.1 What is recursion

If a function can call itself internally, it is a recursive function.
Recursive functions work as well as looping
Since recursion is prone to stack overflow, an exit condition must be added to return

4.2 Use recursion to solve mathematical problems

  1. Ask 123...*n
function fn(n) {
  if(n = 1) {
    return 1
  }
    return n * fn(n-1)
}
console.log(fn(3)) // 6

4.3 Recursive Request: Return corresponding data objects based on id

var data = [{
    id:1,
  name:'household electrical appliances',
  goods: [
    {
      id: 11,
      gname: 'Refrigerator'
    },
    {
        id: 12,
      gname: 'Washing machine'
    }
  ]
},
            {
            id: 2,
              name: 'Clothes & Accessories'
            }
 ]
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 Recursion

5.1 Shallow and Deep Copies

  1. Shallow copies are just one level of copy, and deeper object-level, copy-only references.
  2. Deep copies are multiplayer, and data at each level is copied.
  3. Object.assign (target,... Sources) ES6 new method can be shallowly copied
var obj = {
    id: 1,
  name: 'andy',
  msg: {
   age: 18
  }
}
var o = {}
for(var k in obj) {
  // k is the property name
    o[k] = obj[k]
}
console.log(o)
o.msg.age = 20
console.log(obj) //obj changed

//Syntax sugar with es6
Object.assign(o, obj)

//Deep copy, using recursive methods
function deepCopy(newObj, oldObj) {
    for(var k in oldObj) {
    //Determine what type of attribute values we have
    var item = oldObj[k]
    // Determine if it is an array
    if(item instanceof Array) {
        newObj[k] = []
      deepCopy(newObj[k], item)
      
    } else if(item instanceof Object) {
      //Judging whether it is an object
      newObj[k] = {}
      deepCopy(newObj[k], item)
    } else { // Is a simple data type
         newObj[k] = item
    }  
    
  }
}
deepCopy(o,obj)
console.log(o)

summary

This article mainly shares the use and application of knowledge points such as strict mode of function, higher-order function, closure, recursion, deep copy, shallow copy, etc.If you want to know more, scan the QR code

Keywords: Javascript ECMAScript Attribute

Added by wayang_mbeling on Tue, 03 Mar 2020 03:46:22 +0200