[vue] 在vue项目中如果methods的方法用箭头函数定义结果会怎么样?
var app = nvar app = new Vue({ el: "#app", data: {}, methods: { a: () => { console.log(this); //Window } } }); 为什么我的this指向的是Window?
虽然没有尝试过,但是我估计你是在html里面直接用
this为undefined
因为箭头函数默绑定父级作用域的上下文,所以不会绑定vue实例,所以 this 是undefind
会使this指向的结果返回undefined
this指向的是当前方法,并不会报错
this指向实例最开始实例化的那个作用域
Most helpful comment
虽然没有尝试过,但是我估计你是在html里面直接用
All 10 comments
this为undefined
因为箭头函数默绑定父级作用域的上下文,所以不会绑定vue实例,所以 this 是undefind
会使this指向的结果返回undefined
this指向的是当前方法,并不会报错
this指向实例最开始实例化的那个作用域
var app = nvar app = new Vue({
el: "#app",
data: {},
methods: {
a: () => {
console.log(this); //Window
}
}
});
为什么我的this指向的是Window?
虽然没有尝试过,但是我估计你是在html里面直接用