如何获取跨多个函数返回的变量 - Javascript/jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3531080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:25:30  来源:igfitidea点击:

How to get a variable returned across multiple functions - Javascript/jQuery

javascriptjqueryfunctionclassreturn-value

提问by Kyle

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).

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



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?

全局变量不会强制初始函数等待。并且向后返回四次也不起作用。如果不能返回,如何将修改后的变量传回其初始化函数?或者为什么不回来?

(the maze starts at initFunctionA, ends at functionD)

(迷宫开始于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);
  }
}

采纳答案by strager

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

更改您的回调(在呼叫站点),以便您捕获functionD. 然后,更改functionD以使其返回array2this为方便起见,我添加了对以下示例的访问权限。(此外,如果您想让 JSLint 满意,请确保在“必需”的地方包含分号。)

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);
  }
};

回答by Pointy

You can't make it work with a pattern like you've written there; it's simply not possible in Javascript because there's no such thing as "waiting". Your ajax code has to take a callback parameter (which you've got, though it's not clear where it comes from or what it does), and that initial function should pass in code to do what you need with the array after the ajax call finishes.

你不能让它像你在那里写的那样工作;这在 Javascript 中是不可能的,因为没有“等待”这样的东西。您的 ajax 代码必须采用一个回调参数(您已经获得了该参数,但不清楚它来自哪里或它的作用是什么),并且该初始函数应传入代码以在 ajax 调用后对数组执行所需的操作完成。

回答by ChaosPandion

I would use an object constructor:

我会使用一个对象构造函数:

function ClassOne() {
    this.array2 = [];
}

ClassOne.prototype.initFunctionA = function() {
    // ...
}

ClassOne.prototype.functionD = function(data, array) {
    // Can use array2 EX: this.array2
}

var classOne = new ClassOne();

回答by Matt

This is how I understand your problem: classTwo handles an AJAX call and may modify the result. classOne makes use of classTwo to get some data and needs the resulting data.

这就是我对您的问题的理解:classTwo 处理 AJAX 调用并可能修改结果。classOne 使用 classTwo 来获取一些数据并需要结果数据。

If so, how's this:

如果是这样,这是怎么回事:

classOne = {
  initFunctionA : function() {
    var array = ['a','b','c'];
    classTwo.functionB(this.functionD, array);
  },
  functionD : function(data, array) {
    // This function is called when the AJAX returns.
    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);
  }
}

So classOne.initFunctionA calls classTwo.functionB which sets up an ajax call. When the ajax call completes successfully, classTwo.functionC is called with the result and the initial array. From here, classOne.functionD is called with ret.data.x and the array.

所以 classOne.initFunctionA 调用 classTwo.functionB 来设置一个 ajax 调用。当 ajax 调用成功完成时,会使用结果和初始数组调用 classTwo.functionC。从这里开始,使用 ret.data.x 和数组调用 classOne.functionD。

回答by Kyle

Okay! I found a way to pass variables between functions without:

好的!我找到了一种无需在函数之间传递变量的方法:

  • making global variables
  • making object properties (Chaos's solution)
  • passing parameters
  • 制作全局变量
  • 制作对象属性(Chaos 的解决方案)
  • 传递参数

These three were suggested here as the only ways.

这三种方法在这里被建议为唯一的方法。

Accessing variables from other functions without using global variables

在不使用全局变量的情况下从其他函数访问变量

But, if you you can't pass parameters directly, and you need one function to wait for the other (i.e, can't rely on references), and you're using asynchronous calls to the server in an intermediate function, then your only solution is:

但是,如果您不能直接传递参数,并且您需要一个函数来等待另一个(即不能依赖引用),并且您在中间函数中使用对服务器的异步调用,那么您的唯一的解决办法是:

Using jQuery...

使用jQuery...

Create this object in the DOM (dynamically if you don't want to muddy your markup):

在 DOM 中创建这个对象(动态地,如果你不想混淆你的标记):

<div id='#domJSHandler" style="display: none;"></div>

Then in the function that must wait:

然后在必须等待的函数中:

//Function & Class Set 2
$('#domJSHandler').bind('proceedWithAction', function(event, param1, param2) {
    // action set 2
});

And in the function to be waited on:

在要等待的函数中:

//Function & Class Set 1
// action set 1
$('#domJSHandler').triggerHandler('proceedWithAction', [param1, param2]);

Essentially encase the last actions you need to perform in a jQuery bind custom event on an invisible DOM object. Trigger that event from JS with jQuery's triggerHandler. Pass your parameters and voila!

本质上,您需要在一个不可见的 DOM 对象上的 jQuery 绑定自定义事件中包含您需要执行的最后一个操作。使用 jQuery 的 triggerHandler 从 JS 触发该事件。传递您的参数,瞧!

I'm sure SO will give me crap for this (and for narcissistically accepting my own answer) but I think it's pretty brilliant for a uber-newbie and it worked for me.

我敢肯定 SO 会为此给我废话(以及自恋地接受我自己的答案),但我认为这对超级新手来说非常棒,而且对我有用。

So :p Stack Overflow (jk You've all saved my ass many times and I love you all :)

所以 :p Stack Overflow(jk 你们都救了我很多次,我爱你们所有人 :)