![](/img/trans.png)
[英]Do the parameters passed into an anonymous function in Javascript have special properties?
[英]Is it possible to have parameters for anonymous function?
给定
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
即可创建匿名函数。 Javascript中的new
关键字用于调用作为对象构造函数的函数,构造函数通常使用参数来初始化对象的属性。 只需将匿名函数放入filter()
的参数中即可:
var temp = stuffs.filter(function(o){ return (o.id>=1);});
只要摆脱“新”关键字,它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.