开发环境:javascript
情况一:对象下的函数中
//test.js
var out = {
function inner(){
this
}
}
此时函数中的this表示out对象。
情况二:函数中
//test.js
function inner(){
this
}
此时函数中的this表示全局对象window
开发环境:Vue
情况一:vue组件中
new Vue({
data: {
a: 1
},
created: function () {
console.log('a is: ' + this.a)
}
methods: {
plus: function () {
this.a++
}
}
})
vue组件或者实例中,不管是生命周期钩子函数created还是自定义函数plus,他们中的this都是指当前vue实例。
情况二:回调函数中
//test.vue
methods: {
searchLocations: function() {
var address = this.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({
address: address
}, function(results, status) {
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
}
})
},
buscarLojas: function(center) {
console.log(center)
}
}
此时回调函数function(results, status)会重新将this指向匿名对象(类比java的匿名类),所以其中的this指代父级组件,执行this.buscarLojas
会报错找不到函数。
情况三:箭头函数中
//test.vue
methods: {
searchLocations: function () {
var address = this.search
var geocoder = new window.google.maps.Geocoder()
geocoder.geocode({address: address}, (results, status) => {
if (status === window.google.maps.GeocoderStatus.OK) {
this.buscarLojas(results[0].geometry.location)
} else {
alert(address + ' not found')
}
})
},
buscarLojas: function (center) {
console.log(center)
}
}
箭头函数被绑定到父级上下文,因此其中的this会指向父级组件,针对情况三种的问题,将回调函数中的function改成箭头函数,会将this从匿名对象重新指向外部的vue组件。
参考:
https://stackoverflow.com/questions/51289458/vuejs-this-method-is-not-a-function-how-to-call-a-method-inside-another-method
https://stackoverflow.com/questions/43965714/method-is-not-a-function-in-watcher-callback-vuejs
https://cn.vuejs.org/v2/guide/instance.html?
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this