【JAVAScript】【3】Check code example (including function nesting, closure and window.onload)

JAVAScript verification code instance (including function nesting, closure, method and window.onload)


提示:以下是本篇文章正文内容,下面案例可供参考

1. Function declaration and function expression

2. Function nesting and closure

It is most likely to confuse local variables with mixed variables in a large number of nested functions

1 scope

function f1(){
    
    
  let n = 999
  console.log(n)
}
f1() // 999

function f2(){
    
    
  let n = 999
}
alert(n); // 报错

2 Scope chains in nesting (proximity principle)

insert image description here

insert image description here
The result is 123
insert image description here

3 closures

When you need to access the variables inside the function outside the function, at this time, follow the issue of local variable scope. It seems impossible, the emergence of closures, solves this problem.

function outer(){
    
    
  let name = 'lilei'
  function inner(){
    
    
    return name
  }
  return inner
}
let g = outer()
console.log(g()) // lilei

don't use closures

function outer(){
    
    
  let name = 'lilei'
  return name
}
console.log(outer()) // lilei 

After thinking about it, I found that a single function can also output the required value. Why do we need to introduce closures?
My own understanding is: variable -> function -> class, each layer up is a process of gradual improvement, more logic can be realized through functions, such as data processing, which cannot be realized only by variables.

What are closures?

Closure is a bridge connecting the inside of the function with the outside of the function, and the scope of the outer function can be accessed from the inner function.
One can read the variables in the scope of the function.
Two, the variables in the function can be stored in memory to protect the variables from pollution. And because the closure will store the variable value in the function in the memory, it will consume memory, so the closure cannot be abused, otherwise it will affect the performance of the webpage and cause memory leaks. When you do not need to use the closure, to release the memory in time, you can assign the variable of the memory function object to null.

How to use closures (when counting)

var add = (function(){
    
    
	var counter = 0;
	return funtion (){
    
    return counter += 1;}
})();
add();
add();
add();  //计数器为3

Split code

function outerFunction(){
    
    
	var counter = 0;
	function innerFuntion(){
    
    
		return counter += 1;
	}
	return innerFunction;
}
var add = outerFuntion();
add();
add();
add();   //计数器为3

At this time add forms a closure. A closure consists of two parts, the function and the environment in which the function was created. The environment is made up of local variables in the environment. For the closure add, it consists of the function innerFunction and the variable counter, so add can access the variable counter at this time.

An error occurs when closures are not used

function add(){
    
    
	var counter = 0;
	return counter += 1;
}
add();
add();
add();//一直为1

4. window.onload

  • In order to ensure that the operating modules or objects are loaded before the js code, we have to put the js code at the bottom of the page. But when we design the page, in order to put the js code together, or a place to make the page more concise, it may happen that the objects operated in the code are not loaded. At this time, window.onload has the meaning of existence
  • window.onload is an event that can be triggered immediately after the document is loaded, and an event handler can be registered for this event. Store the code to operate on the object or module in the processing function. That is: window.onload = function () {write operation code here};
  • When the JS code is in front of the layout, you can use window.onload to ensure that the element is executed

Five, examples

Make a verification code The following is the JS idea of ​​the example (the layout is omitted)

insert image description here

Part of the code for the random captcha and the click event is as follows:

1. Math.random()

Because the check code is randomly generated, this example uses the built-in method random() in Math

The Math.random() function returns a floating-point number, a pseudo-random number ranging from 0 to less than 1, that is, from 0 (including 0) up, but excluding 1 (excluding 1), which can be scaled to the required scope. Implements selection of the initial seed to the random number generation algorithm; it cannot be selected or reset by the user.

Create a verification code array arr between 1-9 and af, then use Math.random() to randomly select the elements in the array, and finally generate a complete verification code by splicing str strings

function getStr() {
    
    
    function getRandom(min, max) {
    
    
    //Math.floor为向下取整
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    var str = '';
    for (var i = 0; i < 6; i++) {
    
    
        var num = getRandom(0, arr.length - 1);
        str += arr[num];
    }
    return str;
}

Use function nesting to obtain random numbers and random check codes step by step

Disadvantages: Math.random() does not provide cryptographically secure random numbers. Don't use them for things about security. Use the Web Crypto API instead, and the more precise window.crypto.getRandomValues() method.

2. Click event in windom.onload

window.onload = function () {
    
    
//标签a的点击事件
    var a = document.getElementById('linkbt');
    a.addEventListener('click', function () {
    
    
    document.getElementById('checkCode').innerHTML = getStr()
    //补充一下最好将函数赋给一个变量 
    //var string = getStr();然后innerHTML覆盖
    //document.getElementById('checkCode').innerHTML = string
   
    })

3. The confirmation event in windom.onload

Compare checkCode.innerHTML (check code box) with inputcode.value (input box)

 document.getElementById('button').addEventListener('click',function(){
    
    
        var inputcode = document.getElementById('inputCode').value;
        var checkCode = document.getElementById('checkCode').innerHTML;
        if(inputcode == checkCode){
    
    
            alert('恭喜登录');
        }else{
    
     
            alert('请重新输入');
            document.getElementById('inputCode').value = '';
        }
    })

Summarize

主要是理解闭包函数,内置随机对象,加强实际操作和基础知识。代码有部分为参考,如有错误还望指出

Guess you like

Origin blog.csdn.net/weixin_51612770/article/details/124793697