vue: understanding of this and that

  • When we enter the company, we will find a very common situation, that is, your former developers will often use such a variable: that, self...

  • Why are that and self used? This is what the editor understands. This points to the current object , while that and self are temporary variables. In order to temporarily store this , we ensure that it can be used no matter how we call it. this, and for vue, it can ensure that the value of this remains unchanged and is always a vue instance.
  • Next, I will use a case to briefly show the results:
mounted () {
    this.this_that()
},
methods: {
    this_that () {
        const that = this
        console.log('this1', this)
        setTimeout(function () {
            console.log('this2', this)
            console.log('that3', that)
        }, 1000)
        setTimeout(() => {
            console.log('this4', this)
            console.log('that5', that)
        }, 1500)
    },
}
  • Output result:

  • Analysis:

this1 -- this1 is easy to understand, it must be the vue instance pointed to

this2 -- this2 outputs the window object. Why? First of all, we use the function(){} ordinary function form. The timer is called by the window function, so it points to the window.

that3 -- why does that3 output a vm instance? It's because we defined a that variable outside the timer, and what is output in the timer is only the value of a variable, not the pointer of this.

this4 -- Why is this different from this2? Note that the timer here uses an arrow function. The this of the arrow function points to the object that calls it at the upper level, so here this points to the vue instance.

that5 -- same as that3

Now you should know the reason: we use that to store this in advance, so in this logic, no matter how we call it, we can eventually use this of the vue instance, so we don’t have to consider the pointing problem of this, which is convenient for us The use of this.

Guess you like

Origin blog.csdn.net/qq_45796592/article/details/132341836