一、知识前提
JS作用域有哪些:全局作用域 和 函数作用域。 作用域最大的用处就是隔离变量,不同作用域下同名变量不会有冲突。
(1) JS this指向最终指向的是那个最后调用他的对象。
(2) ES6 箭头函数指向义该函数的作用域。
- 箭头函数没有自己的this,它只会从自己的作用域链的上一层继承this 。所以不可以做构造函数。
二、Vue中箭头函数
总结:data, methods,computed,watch 里不要用箭头函数。
<script type="module">
var msg = 'hello word'; // var 变量,全局变量。
var app = new Vue({
el: '#app',
data(){
return {
msg: 'hi vue' // 挂到vue实例上
}
},
methods: {
showMessage1 () {
console.log('this指向', this) // 指向调用者,也就是这个vue实例子。
console.log('===',this.msg) // hi vue
},
showMessage2: () => {
console.log('this指向', this) // undefined 箭头函数没有this,定义时所在的对象。所以箭头函数的this是固定的,不能改变或者重新绑定。
// 但是methods是一个对象,不能构成作用域,导致箭头函数定义时的作用域是全局作用域,也就是window对象,vue中使用的是严格模式use strict,所以为undefined了.
console.log('====', msg) // hello worc
}
},
created () {
this.showMessage1(); //this 1
this.showMessage2(); //this 2
},
})
</script>
nextTick() 可以用箭头函数
- 箭头函数不能改变this指向,为什么使用nextTick的时候可以使用箭头函数,即nextTick函数定义中的cb.call(ctx)。如下源码中
setTimeout在Vue中要使用箭头函数
例如:
setTimeout (() => {
this.start();
}, 400)