0

I saw a code online. There is a $this=this. In my mind, this line assigns the 'this' of outter function to a variable. It makes the outter 'this' able to use in inner function. But if I use this directly in inner function, there is nothing difference. Did I miss something?

<div id="app">
<ul>
    <li v-for="(item, index) in goods" :key="index">
        <span>name:{{item.name}}</span>
        <span>price:{{item.price.toFixed(2)}}</span>
        <span>number:{{item.num}}</span>
        <br>
        <input type="button" value="+" @click="item.num += 1">
        <input type="button" value="-" @click="item.num -= 1">
    </li>
</ul>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            goods: []
        },
        created () {
            let $this = this;
            setTimeout(() => {
                $this.goods = [
                    {
                        name: 'android',
                        price: 12.99
                    },
                    {
                        name: 'IOS',
                        price: 13.99
                    },
                    {
                        name: 'javaScript',
                        price: 14.99
                    }
                ];

                $this.goods.forEach(item => {
                    item.num = 1;
                });
            }, 3000);
        }
    });
</script>
wl.GIG
  • 306
  • 1
  • 2
  • 13
  • 1
    @AndreiGheorghiu — They do have a scope. https://jsbin.com/wucexigaxa/1/edit?js,console – Quentin Apr 29 '19 at 08:51
  • @Quentin, this is a bit confusing. [Removing the inner `var`](https://jsfiddle.net/websiter/49mexydf/), it behaves like it doesn't. – tao Apr 29 '19 at 09:02
  • @AndreiGheorghiu — The entire point of `var` is that it declares a variable in the scope of the current function. If you remove it then the JS engine will search up the available scopes until it finds a variable of that name or hits the global level. That doesn't mean the scope doesn't exist, just that you aren't putting the variable in that scope. – Quentin Apr 29 '19 at 09:03
  • You're right. I realized it just after I posted my comment. Removing `var` will behave similarly regardless if the function is normal or arrow. Silly me. Thank you. – tao Apr 29 '19 at 09:05

1 Answers1

1

You didn't miss anything.

Since the code uses an arrow function to capture the current value of this, the use of another variable ($this) is pointless.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335