意见:$ this = this为什么对内部函数使用外部'this'?

时间:2019-04-29 08:42:13

标签: javascript vue.js

我在网上看到了一个代码。有一个$ this = this。在我看来,这行代码将外部函数的“ this”分配给变量。它使外部“ this”能够在内部函数中使用。但是,如果我直接在内部函数中使用它,则没有任何区别。我错过了什么?

<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>

1 个答案:

答案 0 :(得分:1)

您什么都没错过。

由于代码使用箭头功能捕获this的当前值,因此使用另一个变量($this)是毫无意义的。