<template>
<div class="home">
1.window的匿名函数 如settimeout(没有箭头)指向是window;函数里面调用要用that变量接一下,才能拿到vue实例,不然指向window
2.js函数 如foreach ,filter(没有箭头)没有指向,所有函数里面调用,直接指向vue,不用做变量替换
3.箭头函数,没有具体的this指向,在它内部使用,由宿主对象决定
3.1匿名函数使用箭头函数写,指向方法的被调用者(vue中是vue)window
3.2 js函数使用箭头写法,
3.3 getValue:()=>{console.log(this)}直接使用this,显示未定义
4 说明:普通函数,都是有this指向的,因为都是window下的函数,所以指向window
</div>
</template>
<script>
export default {
data(){
return {
showEdit:false
}
},
created() {
this.getValue1();
this.getValue2();
this.getValue22();
this.getValue3();
this.getValue33();
this.getValue4();
this.getValue5();
},
methods: {
getValue1(){
let that = this;
setTimeout(function(){
console.log(this);//window
console.log(that);//vue
},1000);
},
getValue2(){
let that = this;
setTimeout(()=>{
console.log(this);//vue
console.log(that);//vue
},1000);
},
getValue22(){
setTimeout(()=>{
console.log(this);//vue
},1000);
},
getValue3(){
[1,2,3,4].forEach((element)=>{
console.log(element,this);//vue
})
},
getValue33(){
let that = this;
[1,2,3,4].forEach(function(element){
console.log(this,element);//undefined
console.log(that,element);//vue
},1000);
},
getValue4(){
let that = this;
let arr1 = [1,2,3,4];
let arr2 = [1,2,3,4];
arr1.filter(function(element){
console.log(this,element);//undefined
console.log(that,element);//vue
return element>2
})
arr2.filter((element)=>{
console.log(this,element);//vue
console.log(that,element);//vue
return element>2
})
},
getValue5:()=>{
console.log(this);//未定义
}
},
}
</script>
<style scoped>
.van-contact-list__add{
z-index: 0;
}
.van-popup{
height: 100%;
}
</style>
【面试点】:vue中关于this的详解
最新推荐文章于 2024-05-08 16:41:41 发布