【问题标题】:Is it possible to have parameters for anonymous function?是否可以为匿名函数提供参数?
【发布时间】:2017-06-19 19:14:31
【问题描述】:

给定

var stuffs = [
    { id : 1, name : "orange"},
    { id : 2, name : "apple"}, 
    { id : 0, name:"grapes"}
];
var filterMethod1 = new function(o){return (o.id>=1);}; // this gives undefined error for o
function filterMethod2(o) {return (o.id>=1);};

为什么使用匿名函数对数组 filter() 方法不起作用?

var temp = stuffs.filter(new function(o){ return (o.id>=1);}); // o is undefined if used this way

使用声明的函数可以正常工作:

var temp = stuffs.filter(filterMethod2);

【问题讨论】:

  • new function(o) {...} 正在尝试将该函数用作构造函数。
  • 你从哪里得到new

标签: javascript anonymous-function function-declaration function-expression


【解决方案1】:

您不需要使用new 来创建匿名函数。 Javascript中的new关键字用于调用函数作为对象的构造函数,参数一般被构造函数用来初始化对象的属性。只需将匿名函数放入filter()的参数中即可。:

var temp = stuffs.filter(function(o){ return (o.id>=1);});

【讨论】:

  • 啊。我懂了。谢谢
【解决方案2】:

只要去掉“new”关键字,它应该可以工作。

【讨论】:

  • 更完整的答案是解释为什么删除 new 关键字将解决 OP 的问题。
  • @Pointy 嗯? .filter() 正在向函数传递值。
  • @mhodges 是的,我没有了解 OP 想要做什么。
  • 谢谢大家。我想我没注意新的关键字
猜你喜欢
  • 2016-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-22
  • 2021-08-06
  • 1970-01-01
相关资源
最近更新 更多