我试图从eg中的函数中的函数访问函数a:

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和function上的bind()。
控制台中出现以下错误:
Uncaught TypeError: this.updateProgress is not a function at eval

你知道怎么做吗?

最佳答案

问题是this的值已更改。每当你输入一个新函数(如用function关键字声明)时,this的值会发生变化。在这种特殊情况下,由setTimeout调用的函数有错误:

setTimeout(function() {
    this.updateProgress(statusurl)
}, 2000)

在过去的几年中,解决方案将是以不同的名称获取对this的引用:
var me = this

setTimeout(function() {
    me.updateProgress(statusurl)
}, 2000)

与其他嵌套函数一样,使用bind的老派会稍微少一些:
setTimeout(function() {
    this.updateProgress(statusurl)
}.bind(this), 2000)

如果你有ES6箭头功能可用(根据你的catch判断你似乎有),那么你甚至不需要使用bind。箭头函数不会更改this的值,因此您只需编写:
setTimeout(() => {
    this.updateProgress(statusurl)
}, 2000)

您对bind的其他用法也同样可以删除。

关于javascript - 嵌套函数的Vue.js访问功能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52453372/

10-11 02:43
查看更多