vue Interview - Summary of Interview Questions 3

1. What is a closure function based on JS and what is it used for?

var i=10;
function add1(){
   alert(i);
   i++;
}
function add2(){
   var j=100;
   alert(j);
   j++;
}

//Test:
//    add1(); //10
//    add1(); //11
//    add1(); //12
//
//    add2(); //10
//    add2(); //10
//    add2(); //10

The reason is simple
i is a global variable and is recycled by GC only when the page is closed;
j is a local variable and is recycled by GC after the function is executed.
Q: Is there any way to make j a global variable?
Yes, write j on the outside (the brain has bamboo slices)
Answer: Closure

function add3(){
  var j=10;
  return function(){
   alert(j);
   j++;
  }
}

//Test:
//   var bibao=add3();
//   bibao(); //10
//   bibao(); //11
//   bibao();//12

implement add3()Then, according to the code, the body of the function (which is a function object) is returned. ----------------console.log(bibao)
// Return value: function(){
//    alert(j);
//    j++;
//   }
Add a bracket()(Let the function body, function object execute), then execute--------------------console.log(bibao()))
//  10


// The difference between parentheses and no parentheses when js calls a function
// Return function body without parentheses
// Parentheses return the result of the body execution

ok, at this point you should know how closures are used. So in vue, where are closures used?
1 Vue computed uses a closure function to pass values

<script type="text/x-template" id="hello-world-template">
    <div>
      <p>Original message: "{{ message }}"</p>
      <p>Computed reversed message: "{{ reversedMessage }}"</p>
      <p>Computed reversed message: "{{ reversedMessage1(2) }}"</p>
	</div>
</script>
<div id="example"></div>

<script>
var vm = new Vue({
    el: '#example',
    template: '#hello-world-template',
    data: {
      message: 'Hello'
    },
    computed: {
      reversedMessage: function() {
        return this.message.split('').reverse().join('')
      },
      reversedMessage1: function() {
        return function reversedMessageget(y) {
          return this.message.split('').reverse().join('')+'___'+y;
        }
      },
    },
    mounted(){
      console.log(this)
    }
  })
</script>

2 data option returns using closures

<script type="text/x-template" id="hello-world-template">
    <div>
       <button @click="add">count</button>
	</div>
</script>
<div id="example"></div>

<script>
var vm = new Vue({
    el: '#example',
    template: '#hello-world-template',
    // When closures are not used
    data: {
      count: 1
    }
    // Use of closures
     data(){
       return {
           count: 1
       }
    },
    method:{
       add(){
          this.count++
       }
    }
  })
</script>


// Encapsulates the current vue file as a component and references it many times elsewhere
// If closures are not used:
// count is a global variable, click on a component and the other two components add up
// If you use closures:
// Click on that one, and that one will increase. Closure is used here to *** not pollute the whole world ***

2. Differences and implementation of anti-shake and throttling based on JS?

Anti-shake: The first time an event is triggered, the function is not executed immediately, but a time limit (such as 200ms) is given, and then:
1 If the scroll event is not triggered again within 200ms, then the function is executed
2If the scroll event is triggered again within 200ms, the current timer is canceled and the timer is restarted
An excellent example of anti-shake:

/*
* fn [function] Functions requiring anti-shake
* delay [number] Milliseconds, anti-shake period value
*/
function debounce(fn,delay){
    let timer = null //With closures, review to avoid global pollution
    return function() {
        if(timer){
            clearTimeout(timer) //Enter the branch statement to indicate that the same event is being triggered while a timer is in progress. So cancel the current timer and restart it
            timer = setTimeout(fn,delay) 
        }else{
            timer = setTimeout(fn,delay) // Entering the branch indicates that the time is not currently being counted, so start a timer
        }
    }
}

window.onscroll = debounce(showTop,1000) // For the sake of observing the effect, we take the break value of a big point and configure it as needed.

// window.onscroll listens for scrollbar scrolling 
// showTop listens for methods executed after scrollbars scroll

Obviously, after reading this code, the reader will surely find that if I keep sliding the scrollbar, the code won't always work.
This is the disadvantage of anti-shake: if an event is triggered continuously within a specified time interval, the calling method will be delayed continuously

Throttle: High frequency event triggered, but executed only once in n seconds, so throttling dilutes the frequency of function execution
Throttle Classic Code:

//Throttle throttle code:
function throttle(fn) {
    let canRun = true; // Save a tag through a closure
    return function () {
         // Determine whether the tag is true at the beginning of the function, or return if it is not true
        if (!canRun) return;
         // Set to false now
        canRun = false;
        // Place the execution of the external incoming function in setTimeout
        setTimeout(() => { 
        // Finally, setting the flag to true (critical) after setTimeout has finished executing indicates that the next loop can be executed.
        // The marker is always false when the timer is not executed and is return ed at the beginning
            fn.apply(this, arguments);
            canRun = true;
        }, 500);
    };
}

function sayHi(e) {
    console.log(e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi));

3. Describe how vue refreshes the page UI from the initialization page - modifying the data?

When the Vue enters the initialization phase, on the one hand, the Vue traverses the properties in the data and uses Object. DefneProperty converts it to getter/setter for data hijacking (not to mention Proxy for Vue3.0); On the other hand, Vue's directive compiler Compiler parses each instruction of the element node, initializes the view, and subscribes to Watcher to update the view, where Watcher adds itself to the message subscriber Dep and initializes.
When the data changes, trigger the setter method in Observer, and immediately call Dep.notify(), which starts traversing all subscribers and calls their update method. Inside the Vue, the diff algorithm is used to update the patch to complete the changes to the subscriber view.

Keywords: Javascript Vue html Interview

Added by jamest on Thu, 23 Dec 2021 05:37:29 +0200