Understand the use of scope and closure in JS (below) (talk about the question)

foreword

The last article talked about scope, closures and some basic knowledge of this use. Friends who are not sure can click the following link to view:
Understand the use of scope and closure in JS (Part 1) (basic definition)
This article The article will continue to focus on these knowledge points, talk about the real interview questions, and help everyone better understand

Examples of real questions:

What are the different usage scenarios of this and how to get the value?

  1. Called in ordinary functions, this is window
  2. call, apply, bind will change the point of this, whoever binds, this points to
  3. As an object method call, this is the current object
  4. This in the class is the class instance itself
  5. Arrow function => , this is the value of the previous scope

Handwritten bind function

Mainly look at the comments, I marked the corresponding position directly

Function.prototype.bind1 = function(){
    
    
    // 参数转化为数组
    const args = Array.prototype.slice.call(argument);
    // 获取this(取出数组的第一项,剩余的就是传递的参数)
    const t = args.shift();
    // 获取绑定mybind的function
    const self = this;
    // 返回一个函数
    return function(){
    
    
    // 执行原函数,并返回结果
        return self.apply(t, args);
    }
}

Application of closures in actual development

Hidden data only provides API to modify data

insert image description here

Create 10 < a >, click to pop up the serial number

Define a outside the loop and define i in the for loop. At this time, i is the block scope in the for loop. Each time it is executed, a block is formed, so the value of i is different, and the corresponding serial number i can be displayed. the value of

let a
for (let i = 0; i < 10; i++) {
    
    
    a = document.createElement('a')
    a.innerHTML = i + '<br>'
    a.addEventListener('click', function (e) {
    
    
        e.preventDefault()
        alert(i)
    })
    document.body.appendChild(a)
}

Summarize

First of all, the point of this, the use of the scene is summarized for everyone, which needs to be well understood. For the handwritten bind function, you can implement it yourself. As long as you understand it, topics such as handwritten call are not a problem. For the application of closures in practice, as long as you can understand the code in the above figure, there is basically no problem. For those who are not very firm in the previous basic knowledge, you can go to the previous article, the link is at the beginning of the article.

OK, this is the end of this article. If you have any questions, you can discuss it in the comment area. If it is helpful to you, you can like, follow and support it~ I will continue to bring front-end related content in the future.

Guess you like

Origin blog.csdn.net/weixin_45745641/article/details/123891011