背景:
以下代码是使用vue-cli初始化vue项目时,在app.vue
中添加的内容。
<template>
<div id="app">
<img src="./assets/logo.png" />
<router-view />
</div>
</template>
<script>
export default {
name: 'App',
data() {
return {
prop: 'haha'
}
},
mounted() {
this.test()
},
methods: {
test() {
let arr = [1]
arr.forEach(elem => {
console.log('this', this)
debugger
})
}
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
问题描述:
我在test()
方法中使用debugger
想获取this
的内容,通过console.log
可以打印出我预料到的内容(即VueComponent
对象信息)。但是通过在chrome中打断点,或者debugger的方式,this
的值却是undefinded
。
请问出现这种情况的原因是什么?
问题补充:
附上调试图
很感谢有人关注这些问题,一些评论提到“是不是还没跑到那一步你就查看this
的数据了”;
实际情况是,我的debugger
写在console.log('this', this)
下,且当程序执行到debugger
时,console.log
已经打印出了this
的信息,但是将鼠标放上this
上时,还是显示undefinded
我总结了一下这个问题,可以在 这篇博客看,就是因为箭头函数 被babel打包改变了,this通过_this或者_this2 这个变量保存了,控制台直接输入this无法输出,而输入_this或者_this2,就能取到期望值。 https://blog.csdn.net/rudy_zh...