是否可以为匿名函数设置参数?

时间:2017-06-19 19:14:32

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

鉴于

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

2 个答案:

答案 0 :(得分:4)

您无需使用new来创建匿名函数。 Javascript中的new关键字用于将函数作为对象构造函数调用,并且构造函数通常使用这些参数来初始化对象的属性。只需将匿名函数放入filter()。:

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

答案 1 :(得分:2)

只需删除“new”关键字,它就应该有效。

相关问题