【问题标题】:Passing methods as a argument in JavaScript在 JavaScript 中将方法作为参数传递
【发布时间】:2014-10-25 19:34:47
【问题描述】:

我正在编写一个函数,它允许我通过将另一个函数作为值传递来显示数组的值。

这段代码运行良好:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}
forEach(["foo", "bar", "qux"], alert);

但是如果我尝试传递带有属性的函数,它会抛出错误:

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
    action(array[i]);
}
forEach(["foo", "bar", "qux"], console.log);

如果我这样做: action.log(array[i]); 它工作得很好,但这只会让我传递带有.log 属性的函数。有什么方法可以编写一个函数,允许我将另一个函数和属性作为值传递?

【问题讨论】:

标签: javascript function methods functional-programming this


【解决方案1】:

问题不在于使用对象的方法,而是console.log 特定的问题。 Bug report here。对于console.log,具体可以绑定上下文,例如:

forEach(["foo", "bar", "qux"], console.log.bind(console));

其他方法也可以,例如:

var x = {
    test: function(str){
        alert(str);
    }
}

forEach(["hello", "world"], x.test);

【讨论】:

    【解决方案2】:

    你可以使用类似的东西

    function forEach(array, action) {
    for (var i = 0; i < array.length; i++)
      action(array[i]);
    }
    forEach(["foo", "bar", "qux"], function(x){ return console.log(x) });
    

    【讨论】:

      【解决方案3】:

      在 Chrome 中,这是预期的,因为 console.info 期望它的“this”引用是控制台,而不是窗口。否则,我发现它在 Firefox 32 / IE 中工作。

      https://code.google.com/p/chromium/issues/detail?id=48662

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-16
        • 2013-02-20
        • 2010-10-06
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多