【问题标题】:OOP javascript, from a AJAX 'statement' in a method, how call an another method of the class?OOP javascript,从一个方法中的AJAX'语句',如何调用该类的另一个方法?
【发布时间】:2019-04-17 16:17:22
【问题描述】:

我有这个简单的课程:

class myCustomClass{

    foo(value){
        //do some stuff
    }

    faa(){
        //do some stuff
        $.getJSON( someUrl, function(data) {
            // how call the method foo(value) here ?
            this.foo('fii'); // error occured here, because 'this' is not in 'class' context        
        }
    }
}

当我使用 AJAX 语句时,如何在方法 faa 中使用方法 'foo(value)' ? 我不能在这里使用简单的“this.foo(value)”,因为 AJAX 语句中“this”的上下文不是“类”上下文(而是 AJAX 上下文)

【问题讨论】:

  • 来自 c# 我认为您需要在 ajax 调用中实例化该类,然后使用它。

标签: javascript jquery ajax oop


【解决方案1】:

您需要在外部范围内“缓存”对类的引用,以便可以在 AJAX 回调的内部范围内使用它,如下所示:

faa() {
  var _class = this; // cache class reference here

  // do some stuff

  $.getJSON(someUrl, function(data) {
    _class.foo('fii'); // use it here
  });
}

您也可以使用箭头函数,假设您永远不需要使用回调的内部范围:

faa() {
  // do some stuff

  $.getJSON(someUrl, (data) => {
    this.foo('fii'); // use it here
  });
}

【讨论】:

    【解决方案2】:

    我一般都是这样的,

    class myCustomClass {
    
        foo(value) {
            // do some stuff
        }
    
        faa() {
            var me = this;
            // do some stuff
            $.getJSON(someUrl, function(data) {
                // how call the method foo(value) here ?
                me.foo('fii'); // error occured here, because 'this' is not in 'class' context        
            });
        }
    }
    

    【讨论】:

    • 抱歉,有点晚了,重复
    猜你喜欢
    • 1970-01-01
    • 2011-01-15
    • 2023-04-09
    • 2017-10-17
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多