如何获取跨多个函数返回的变量 - Javascript / jQuery [英] How to get a variable returned across multiple functions - Javascript/jQuery

查看:119
本文介绍了如何获取跨多个函数返回的变量 - Javascript / jQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题总结是为了弄清楚如何在javascript函数之间传递变量,无需:返回变量,在主函数之间传递参数,使用全局变量,强制函数1等待函数2完成。我想出了一个jQuery解决方案,并张贴在下面(在答案部分)。

This question in summary is to figure out how to pass variables between javascript functions without: returning variables, passing parameters between primary functions, using global variables, and forcing function 1 to wait for function 2 to finish. I figured out a jQuery solution and posted in below (in the answers section).

旧帖:的四个功能,每个以不同的方式互相呼唤。在它的末尾,我需要返回到初始化函数的最终修改的产品(数组)。

Old Post: I initialize a set of four functions, each calling on each other in a different way. At the end of it, I need the final modified product (an array) returned to the initializing function.

全局变量不强制初始函数等待。和向后返回四次也不工作。如果你不能返回它,你如何将一个修改的变量传递回它的初始化函数?

Global variables don't force the initial function to wait. And returning it backwards four times doesn't work either. How do you pass a modified variable back to its initializing function, if you can't return it? Or why isn't it returning?

(迷宫始于 initFunctionA ,结尾为 functionD

classOne = {
  initFunctionA : function() {
    classTwo.functionB(functionD, array);
    // I NEED ACCESS TO ARRAY2 HERE
  },
  functionD : function(data, array) {
    var array2 = // modifications to array
  }
}

{...}

classTwo = {
  functionB : function(callback, array) {
    $.ajax({
      success: function(ret){
        classTwo.functionC(ret, callback, array)
      }
    });
  },
  functionC : function(ret, callback, array) {
     callback(ret.data.x, array);
  }
}


推荐答案

更改您的回调(在调用站点),以便捕获 functionD 的返回值。然后,更改 functionD ,以便它返回 array2 。为了方便起见,我添加了访问下面的示例。 (另外,如果您想让JSLint快乐,请务必在其中加入分号。)

Change your callback (at the call site) such that you capture the return value of functionD. Then, change functionD so that it returns array2. I've added this access to the example below as a convenience. (Also, be sure to include semicolons where "required" if you want to make JSLint happy.)

classOne = {
  initFunctionA : function() {
    var self = this;

    classTwo.functionB(function() {
        var array2 = functionD.apply(self, arguments);

        // ACCESS ARRAY2 HERE
    }, array);
  },
  functionD : function(data, array) {
    var array2 = // modifications to array

    return array2;
  }
};

{...}

classTwo = {
  functionB : function(callback, array) {
    $.ajax({
      success: function(ret){
        classTwo.functionC(ret, callback, array)
      }
    });
  },
  functionC : function(ret, callback, array) {
     callback(ret.data.x, array);
  }
};

这篇关于如何获取跨多个函数返回的变量 - Javascript / jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆