Javascript 来自嵌套函数的Vuejs访问函数
我试图从函数中的函数访问函数a,例如:Javascript 来自嵌套函数的Vuejs访问函数,javascript,vue.js,vuejs2,axios,Javascript,Vue.js,Vuejs2,Axios,我试图从函数中的函数访问函数a,例如: functionA () { functionB () { functionC () { #want to call functionA from here } } } 以下是我正在使用的代码: updateProgress: function (statusurl){ axios({ method: 'get', url: statusurl,
functionA () {
functionB () {
functionC () {
#want to call functionA from here
}
}
}
以下是我正在使用的代码:
updateProgress: function (statusurl){
axios({
method: 'get',
url: statusurl,
dataType: 'json',
headers: {'Content-Type': 'application/json; charset=utf-8'},
async: true,
data: {}
})
.then(function (response) {
var data = response.data
if (data['state'] !== 'PENDING' && data['state'] !== 'PROGRESS') {
if ('result' in data) {
// show result
console.log('result: ' + data['result'])
}
else {
// something unexpected happened
console.log('state: ' + data['state'])
}
}
else {
// rerun in 2 seconds
setTimeout(function() {
this.updateProgress(statusurl)
}, 2000)
}
}.bind(this))
.catch(e => {
console.log('error: ' + e)
})
如您所见,我使用functionC中的this.function和functionA上的bind()
我在控制台中遇到以下错误:
Uncaught TypeError: this.updateProgress is not a function at eval
你知道怎么做吗?问题是
this
的值已更改。每次输入一个新函数(如用function
关键字声明的那样),this
的值都会改变。在这种特定情况下,setTimeout
调用的函数出现故障:
setTimeout(function() {
this.updateProgress(statusurl)
}, 2000)
在过去的几年中,解决方案是以不同的名称引用此
:
var me = this
setTimeout(function() {
me.updateProgress(statusurl)
}, 2000)
与其他嵌套函数一样,使用bind
的老式方法稍微少一些:
setTimeout(function() {
this.updateProgress(statusurl)
}.bind(this), 2000)
如果您有可用的ES6 arrow函数(从您的catch
判断,您似乎有),那么您甚至不需要使用bind
。箭头函数不会更改此的值,因此您只需编写:
setTimeout(() => {
this.updateProgress(statusurl)
}, 2000)
您对bind
的其他使用也可以类似地删除。pretty函数(响应)
绑定语法无论如何都是错误的。为什么不直接使用箭头函数,即response=>