如何调用存储在jQuery数组中的函数

How do I call a function stored in a jQuery array?

本文关键字:数组 jQuery 函数 存储 何调用 调用      更新时间:2023-09-26

我在jQuery中有一个钩子数组,在我将数据加载到网格之前执行。然而,在一种情况下,我想要删除钩子,然后将其添加回来以供以后使用。不管我在做什么,都不太对劲……这可能是语法错误,因为我对jQuery还不太熟悉。任何帮助将不胜感激,谢谢!

当前代码:

var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(function(report) { preLoad(report); });

编辑事实证明,问题出在代码的其他地方。但是,我仍然想知道如何最好地实现这一点。

访问它的方式与存储在任何其他数组中的其他变量相同。

 this.opts.hooks.preLoad[0](myReport)

你就不能像这样添加你删除的函数吗?

var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(preLoad);

你确定它总是你想要删除的数组中的最后一个吗?

这可能与您在将函数推回堆栈时"封装"参数"report"有关。

试着这样做:

var preLoad = this.opts.hooks.preLoad.pop();
//stuff happens
//now I want to add the preLoad hook back
this.opts.hooks.preLoad.push(preLoad);

我已经测试过了http://jsfiddle.net/fWRez/

您给出的示例与jQuery无关,而是纯Javascript。另外,要注意你在例子中所做的是……不正确的。

var ReportManager {
   ...
   replace: function(report) {
      var preLoad = this.opts.hooks.preLoad.pop();
      //stuff happens
      //now I want to add the preLoad hook back
      this.opts.hooks.preLoad.push(function(report) { preLoad(report); });
   }
}

如果你执行这个:

replace(null);
replace({foo:'bar'});
replace(null);

你的this.opts.hooks.preLoad数组看起来像这样:

Array(
   0: function(report) { return function(report) { return function(report) { ... } } }
)

因为每次执行代码时都将函数包装到自身中。我不知道为什么你需要把poppush再放回去,但这看起来很奇怪。

此外,Javascript是一种非常灵活的语言;这意味着你可以做很多奇怪的事情,比如
"hello".concat(" world");            // -> 'hello world'
0.toString();                        // -> '0'
(function(a) { return a; })("foo");  // -> 'foo'
(function() { return false; })() || (function() { return true; })(); // -> true (executes both functions)
(function(i) { return [i*2,i*3,i*4]; })(2)[1]; // -> 6
$('selector')[0];                    // ...
// etc.