一、普通函數中的this
這是vue文檔里的原話:
All lifecycle hooks are called with their 'this' context pointing to the Vue instance invoking it.
意思是:在Vue所有的生命周期鈎子方法(如created,mounted, updated以及destroyed)里使用this,this指向調用它的Vue實例,即(new Vue)。
<div id="app"> <button class="btn btn-primary" v-on:click="on()">點擊添加並查看this</button> <ul class="list-group" v-for="item in list"> <li class="list-group-item">{{item}}</li> </ul> </div> <script> new Vue({ el: "#app", data: { list: ["banner", "orange", "apple"] }, methods: { on: function() { alert(this.list); this.list.push("Potato") } }) </script>
實例:這里的this指向的是new Vue這個對象。new Vue也可以寫成var C=new Vue({}).所以這里的this指向的是C。
二、箭頭函數中的this
箭頭函數沒有自己的this, 它的this是繼承而來; 默認指向在定義它時所處的對象(宿主對象),而不是執行時的對象, 定義它的時候,可能環境是window; 箭頭函數可以方便地讓我們在 setTimeout ,setInterval中方便的使用this。
這里箭頭函數指向window。