[Pre-parsing, scope, variable access rules, recursive functions, combined use of functions and events]

Pre-parsing (emphasis)

  • Pre-parsing is actually talking about the compilation and execution of js code
  • js is an interpreted language, that is, before the code is executed, the code is read through (first find the declared type, such as: var, function) and explained, and then the code is executed
  • In other words, when our js code is running, it will go through two links: interpreting the code and executing the code

explain code

Because it is interpreted before all codes are executed, it is called pre parsing (pre-interpretation)

There are two things to explain

declarative function

In memory, first declare that a variable name is a function name, and the content represented by this name is a function

var
  • keywords
  • First declare a variable name in memory
  • Look at the following piece of code
<script>
fn()
console.log(num)
function fn() {
      
      
console.log('我是 fn 函数')
}
var num = 100
</script>
  • After preparsing, it can be transformed into
<script>
function fn() {
      
      
console.log('我是 fn 函数')
}
var num//变量提升只提升声明部分,只提升到当前作用域的最顶端,赋值还是在下边
fn()
console.log(num)
num = 100
    //函数提升优先于变量提升,变量提升只提升声明部分
</script>
  • Assignment functions will be pre-parsed according to the rules of the var keyword

Scope (emphasis)

  • What is scope, is the scope within which a piece of code can take effect
  • This code is not available everywhere, and the scope of use of this variable is the scope

global scope

Location: Define the variable definition in the script tag, the area outside the function, has a global scope, and can be used anywhere

Life cycle: Opening a page is like forming a global scope, and the page is destroyed when the global scope is closed; there is no declaration inside the function, but the assigned value can be understood as a global variable

Note: There is a window object in the global scope, which can be accessed directly;

  • The global scope is the largest scope

  • Variables defined in the global scope can be used anywhere

  • When the page is opened, the browser will automatically generate a global scope window for us

  • This scope will always exist until the page is closed and destroyed

    // 下面两个变量都是存在在全局作用域下面的,都是可以在任意地方使用的
    var num = 100
    var num2 = 200
    
    

local scope

Location: defined inside the function, variables can only be accessed inside the function, not outside

Life cycle: generated when the function is called, and destroyed when the function is called

​ Calling a function once will generate a local scope, and multiple local scopes are independent of each other

Note: Variables defined inside functions have local scope, not in if or for

  • The local scope is a relatively small scope opened up under the global scope

  • Variables defined in a local scope can only be used inside this local scope

  • In JS only functions can generate a local scope, nothing else

  • Every function is a local scope

    // 这个 num 是一个全局作用域下的变量 在任何地方都可以使用
    var num = 100
    
    function fn() {
      // 下面这个变量就是一个 fn 局部作用域内部的变量
      // 只能在 fn 函数内部使用
      var num2 = 200
    }
    
    fn()
    
    

Variable access rules (emphasis)

  • With the scope, the variable has a scope of use, and there are rules of use
  • Variable usage rules are divided into two types, access rules and assignment rules

access rules

  • When I want to get the value of a variable, we call this behavior access

  • Rules for Acquiring Variables: The Principle of Proximity

    • First, look inside your own scope, if there is, use it directly
    • If not, go to the upper level scope to find, if there is, use it
    • If not, continue to search in the upper scope, and so on
    • If there is no such variable until the global scope, then an error will be reported directly (the variable is not defined)
    var num = 100
    
    function fn() {
      var num2 = 200
      
      function fun() {
        var num3 = 300
        
        console.log(num3) // 自己作用域内有,拿过来用
        console.log(num2) // 自己作用域内没有,就去上一级,就是 fn 的作用域里面找,发现有,拿过来用
        console.log(num) // 自己这没有,去上一级 fn 那里也没有,再上一级到全局作用域,发现有,直接用
        console.log(a) // 自己没有,一级一级找上去到全局都没有,就会报错
      }
      
      fun()
    }
    
    fn()
    
    
  • Variable access rules are also called scope lookup mechanisms

  • The scope search mechanism can only be searched upwards, not downwards.

    function fn() {
      var num = 100
    }
    fn()
    
    console.log(num) // 发现自己作用域没有,自己就是全局作用域,没有再上一级了,直接报错
    
    

Assignment rules

  • When you want to assign a value to a variable, you must first find the variable and assign it

  • Variable assignment rules: the principle of proximity

    • First look inside your own scope, and assign directly if there is one
    • If not, go to the upper scope to find it, if there is, assign it directly
    • If there is no search in the upper level scope, then assign the value directly
    • If there is no global scope, then define this variable as a global variable and assign it a value
    function fn() {
      num = 100
    }
    fn()
    
    // fn 调用以后,要给 num 赋值
    // 查看自己的作用域内部没有 num 变量
    // 就会向上一级查找
    // 上一级就是全局作用域,发现依旧没有
    // 那么就会把 num 定义为全局的变量,并为其赋值
    // 所以 fn() 以后,全局就有了一个变量叫做 num 并且值是 100
    console.log(num) // 100
    
    

recursive function

  • What is a recursive function

  • In the programming world, recursion is a means of calling yourself

  • Recursive function: Call the function itself directly or indirectly inside the function

  • Recursion needs an exit, and if there is no exit, dead recursion will be formed (Maximum call stack size exceeded: stack overflow\memory overflow)

    // 下面这个代码就是一个最简单的递归函数
    // 在函数内部调用了自己,函数一执行,就调用自己一次,在调用再执行,循环往复,没有止尽
    function fn() {
      fn()
    }
    fn()
    
    
  • In fact, recursive functions are very similar to loops

  • It needs initialization, self-increment, code execution, and conditional judgment, otherwise it is an endless recursive function, which we call dead recursion

Simple implementation of a recursive

  • Let's first use a recursive function to simply achieve an effect

  • Requirement: Find the sum of 1 to 5

    • First count 1 + 2 to get 3
    • Add 3 + 3 to get 6
    • Then count 6 + 4 to get 10
    • Then count 10 + 5 to get 15
    • Finish
  • Start writing, write the recursive function first to write the end condition (in order to avoid "dead recursion")

    function add(n) {
      // 传递进来的是 1
      // 当 n === 5 的时候要结束
      if (n === 5) {
        return 5
      }
    }
    
    add(1)
    
    
  • Then write our recursive processing when the conditions are not met

    function add(n) {
      // 传递进来的是 1
      // 当 n === 5 的时候要结束
      if (n === 5) {
        return 5
      } else {
        // 不满足条件的时候,就是当前数字 + 比自己大 1 的数字
        return n + add(n + 1)
      }
    }
    add(1)
    
    

Combining functions and events

event:

onclick: click event

onmouseover: mouse over event

onmouseout: mouse out event

Simple example: (little calculator implementation case)

<!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>
    <style>
        main {
      
      
            width: 1000px;
            margin: 100px auto;
            text-align: center;
            line-height: 200px;
        }

        input,select,button{
      
      
            display: inline-block;
            border: none;
            width: 50px;
            height: 50px;
            background-color: rgba(127, 255, 212, 0.548);
            text-align: center;
            line-height: 50px;
        }
    </style>
</head>

<body>
    <main>
        <input type="text" id="text1">
        <select id="select">
            <option>+</option>
            <option>-</option>
            <option>*</option>
            <option>/</option>
            <option>%</option>
        </select>
        <input type="text" id="text2">
        <button id="btn">=</button>
        <input type="text" id="text3">
    </main>
</body>

</html>
<script>
    var oText1 = document.getElementById("text1")
    var oText2 = document.getElementById("text2")
    var oText3 = document.getElementById("text3")
    var oselect = document.getElementById("select")
    var oBtn = document.getElementById("btn")
    oBtn.onclick = function () {
      
      
        switch (oselect.value) {
      
      
            case "+":
                oText3.value = Number(oText1.value) + Number(oText2.value);
                break;
            case "-":
                oText3.value = Number(oText1.value) - Number(oText2.value);
                break;
            case "*":
                oText3.value = Number(oText1.value) * Number(oText2.value);
                break;
            case "/":
                oText3.value = Number(oText1.value) / Number(oText2.value);
                break;
            case "%":
                oText3.value = Number(oText1.value) % Number(oText2.value);
                break;
            default:
                break;
        }
    }
</script>

Easy to understand objects

Object: Everything is an object, and an object is a combination of a series of attributes and behaviors

  • Object is a complex data type

  • In fact, it is complicated, but it is not very complicated. It is just a collection that stores some basic data types.

    var obj = {
      num: 100,
      str: 'hello world',
      boo: true
    }
    
    
  • here {}is {}not the same as in the function

  • The code is written in the function, and some data is written in the object

  • An object is a collection of key-value pairs

  • {}Each key in it is a member

  • In other words, we can put some data in an object, then they will not interfere with each other

  • In fact, we prepare a house, put the data we want in it, and then give the address of the house to the variable name. When we need a certain data, we can find the corresponding house according to the address stored in the variable name, and then Go to the house to find the corresponding data

  • The show method can be used to display information, and it can only be displayed after being called (the method in the object). When calling, you need "object. method" to call

    <script>
        var obj={
            
            
            //name:"张三",----》键值对,  键值对与键值对之间用,隔开,最后一个不用,
            name:"张三",
            age:14,
            eat(){
            
            
                console.log("火锅")
            },//show方法是可以用来展示信息的,调用后才能展示出来(对象内的方法)调用时需要对象.方法去调用
                show(){
            
             console.log("name"+obj["name"]+"age"+obj["age"])
                }
        }
        console.log(obj);//打印对象
        obj.show();//对象调用方法   .语法
        obj["show"];//对象调用方法   []语法
        //对象访问语法   .语法/[]语法
        var obj = {
            
            }
        //  .  语法
        	obj.name = "张三";
            obj.age = 16; 
         
        //  [ ]语法
        	obj["name"] = "张三";
            obj["age"] = 16;  
        //增:obj.name = "张三"
       // 删:delete obj.name
        //改:
        	obj.name = "李四";
    </script>
    

create an object

  • Create an object literally

    // 创建一个空对象
    var obj = {}
    
    // 像对象中添加成员
    obj.name = 'Jack'
    obj.age = 18
    
    
  • Create objects with built-in constructors

  • Object is the constructor function built into js to us, which is used to create an object

    // 创建一个空对象
    var obj = new Object()
    
    // 向对象中添加成员
    obj.name = 'Rose'
    obj.age = 20
    
    

Guess you like

Origin blog.csdn.net/qq_45349018/article/details/121770820