【问题标题】:Add Functions with params to Array Javascript (Node.js)将带有参数的函数添加到数组 Javascript (Node.js)
【发布时间】:2016-09-27 23:25:44
【问题描述】:

我想将带有参数的函数推送到数组而不执行它们。这是我迄今为止尝试过的:

 var load_helpers = require('../helpers/agentHelper/loadFunctions.js');
 var load_functions = [];
 load_functions.push(load_helpers.loadAgentListings(callback , agent_ids));
 load_functions.push(load_helpers.loadAgentCount(callback , agent_data));

但是通过这种方式,函数会在推送时执行。 This Question 提供了类似的示例,但没有参数。在此示例中如何包含参数?

【问题讨论】:

  • 你绑定数组结构了吗?否则,我建议使用包含对函数和参数的引用的对象的解决方案。
  • 是的,我需要将此数组传递给async.parallel([] , callback()); 对象可能有解决方法。

标签: javascript arrays node.js


【解决方案1】:

您必须将参数绑定到函数。 第一个参数是'thisArg'。

function MyFunction(param1, param2){
   console.log('Param1:', param1, 'Param2:', param2)
}

var load_functions = [];
load_functions.push(MyFunction.bind(undefined, 1, 2));
load_functions[0](); // Param1: 1 Param2: 2

【讨论】:

  • 简单而精确。!谢谢你。 :)
  • 不,您不必必须绑定参数,尽管这是一种方法。使用箭头函数编写 () => Myfunction(1, 2) 更具可读性和惯用性。
【解决方案2】:

推送你想要的功能:

load_functions.push(
  () => load_helpers.loadAgentListings(callback, agent_ids),      
  () => load_helpers.loadAgentCount   (callback, agent_data)
);

【讨论】:

    【解决方案3】:

    你可以用这样的函数包装添加的元素,让我们模拟load_helpers

    var load_helpers = {
      loadAgentListings: function(fn, args) {
        args.forEach(fn)
      }
    }
    

    并尝试以这种方式使用它:

    var a = []
    
    a.push(function() {
      return load_helpers.loadAgentListings(function(r) {
        console.log(r)
      }, ['a', 'b', 'c'])
    })
    
    a[0]() // just execution
    

    一切都取决于你想要传递额外参数的级别,第二个概念证明

    var a = []
    
    a.push(function(args) {
      return load_helpers.loadAgentListings(function(r) {
        console.log(r)
      }, args)
    })
    
    a[0](['a', 'b', 'c']) // execution with arguments
    

    使用绑定:

    var a = []
    
    a.push(load_helpers.loadAgentListings.bind(null, (function(r) {return r * 2})))
    
    console.log(a[0]([1, 2, 3])) // execution with additional parameters
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 2017-06-19
      • 1970-01-01
      • 2014-10-31
      • 2016-04-02
      • 1970-01-01
      相关资源
      最近更新 更多