javascript - 在闭包中调用父函数

标签 javascript node.js asynchronous soap callback

我真的很难尝试在异步 soap 请求中调用对象函数。基本上可以归结为:

function Thing(request, response) {

    this.foo = function() {
        console.log("this is foo");
    }

    this.doThing = function() {
        // Get SOAP args
        args = { foo: this.request.cookies.foo };
        // From the SOAP npm package library
        soap.createClient(function(err, client) {
            client.doSomething(args, function(err, result) {
                // Somehow call foo(); <--- CAN'T FIND A WAY TO DO THIS
            });
        });
    }
}
// Make it so I can access this.request and this.response somehow
Thing.prototype = Object.create(AbstractThing); 

我已经尝试了很多东西,但我相信这从根本上归结为我无法在任何异步 soap 函数中调用 this.foo() 的事实。尽管我可以将回调函数传递给 createClient,如下所示:

function Thing(request, response) {

    this.foo = function() {
        console.log("this is foo");
    }

    this.sendSoap = function(err, client) {
        // Get SOAP args
        args = { 
            foo: this.request.cookies.foo <--- this.cookies undefined
        }; 
        client.doSomething(args, function(err, result) {
            // Somehow call foo(); <--- CAN'T FIND A WAY TO DO THIS
        });
    }

    this.doThing = function() {
        // From the SOAP npm package library
        soap.createClient(this.sendSoap);
    }
}
// Make it so I can access this.request and this.response somehow
Thing.prototype = Object.create(AbstractThing); 

我不能再访问 this.request.cookies 因为 this 现在在 sendSoap 闭包内部被调用。我不知道为什么 javascript 将函数作为对象,但我有点沮丧。

我已经尝试了很多很多事情,但无法想出一种方法来做到这一点并且需要这样做,因为对 foo 的原始调用实际上是我在一个状态下使用的递归函数-itterator 模式,用于在我用 Java 编写的 SOAP Web 服务中进行身份验证。

我能想到的最后一种方法是修改 SOAP npm 包,这样我就可以将 this.cookies 传递给 createClient 而不仅仅是回调。

我真的没有主意了。任何帮助将不胜感激。

最佳答案

原因是回调函数中的 this 通常会引用全局窗口范围。

this 是 JS 开发人员常见的痛苦来源,而且通常它并不像您认为的那样。您可以在线搜索完整的详细信息。

为什么不这样关闭呢?

function Thing(request, response) {

    this.foo = function() {
        console.log("this is foo");
    }

    this.doThing = function() {
        var self = this; //Closure to the Thing function
        // Get SOAP args
        args = { foo: this.request.cookies.foo };
        // From the SOAP npm package library
        soap.createClient(function(err, client) {
            client.doSomething(args, function(err, result) {
                self.foo();
            });
        });
    }
}

关于javascript - 在闭包中调用父函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127400/

相关文章:

javascript - 使用 angularfire : 0. 8.0 startAt 和 endAt 未按预期工作

javascript - 滚动 "scrollable"div 时,CKeditor 内联编辑器保留在屏幕上

javascript - Sequelizejs - 然后结果问题

javascript - 如何从异步调用返回响应?

javascript - jQuery - 使用全局数组并等待 $get 加载检索到的数据?

javascript - jQuery 获取 anchor 值

javascript - Video.js 播放器在处理并重新初始化后无法播放

javascript - 如何在 Node.js 中与 Net 建立持久连接?

node.js - AWS Step/Lambda - 在运行之间存储变量

python - 非阻塞扭曲 xmlrpc