【问题标题】:Vuejs access function from nested fuctionVue Js从嵌套函数访问函数
【发布时间】:2018-09-22 04:01:52
【问题描述】:

我正在尝试从 A 中的函数中的函数访问函数 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.functionA,在 functionA 上使用 bind()。

我在控制台中收到以下错误:

Uncaught TypeError: this.updateProgress is not a function at eval 

你知道怎么做吗?

【问题讨论】:

  • function (response) 绑定语法无论如何都是错误的。为什么不直接使用箭头函数,即response =>

标签: javascript vue.js vuejs2 axios


【解决方案1】:

问题是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 的其他用途同样可以删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2019-06-14
    • 2018-10-23
    相关资源
    最近更新 更多