来自 ajax 回调的 Javascript(原型(prototype))方法调用

标签 javascript jquery ajax

我写了一些像这样的面向对象的 Javascript:

function MyClass(){

    this.SomeFunc(arg1){
        result = <some processing on arg1>;
        return result;
    };

    this.SomeOtherFunc(){
        return $.ajax({
            <some restful call>
        }).done(function(){
            var localvar = this.SomeFunc(<value obtained by restful call>);
            <some operations with localvar>;
        });
    };
};

var myObj = new MyClass();
myObj.SomeOtherFunc();

而且我在 Web 控制台中收到错误消息:“this.SomeFunc 不是函数”。如果我直接在一个函数中调用它,就没有问题。调用仅在 Ajax 内部失败。进行此函数调用的正确方法是什么?

最佳答案

this 在你的回调函数中不同于 this 引用 SomeFunc,尝试做:

this.SomeOtherFunc(){
    var thatFunc = this; //get hold of this
    return $.ajax({
        <some restful call>
    }).done(function(){
        var localvar = thatFunc.SomeFunc(<value obtained by restful call>);
        <some operations with localvar>;
    });
};

关于来自 ajax 回调的 Javascript(原型(prototype))方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696411/

相关文章:

javascript - 在网页上禁用剪贴板和打印屏幕

jquery - 禁用初始自动 ajax 调用 - DataTable 服务器端分页

jquery - allow-control-allow-origin : * present in response, 但它仍然显示错误

php - 将 php 表单发送到 2 个位置

javascript - 在不同的 attr 中定义的指令 attr 内的回调函数

javascript - 用户信息作为前端的全局变量

javascript - 无法访问 Jasmine 测试用例中的范围变量

javascript - 在图标上动态添加 UI Bootstrap Popover?

javascript - 如何在 jQuery/HTML 中具有多列的 ListView 上使用数据过滤器属性?

javascript - 一个简单的 jquery 片段来验证用户的电子邮件地址