微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 为什么我需要在node.js中写“function(value){return my_function(value);}”作为回调?

全新的JS,所以请原谅,如果这是令人难以置信的明显.

假设我想使用映射字符串的功能f过滤字符串列表 – >布尔.这样做:

filteredList = list.filter(function(x) { return f(x); })

这失败了:

filteredList = list.filter(f)

为什么???

代码示例:

~/projects/node (master)$node
> var items = ["node.js","file.txt"]
undefined
> var regex = new RegExp('\\.js$')
undefined
> items.filter(regex.test)
TypeError: Method RegExp.prototype.test called on incompatible receiver undefined
    at test (native)
    at Array.filter (native)
    at repl:1:8
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
> items.filter(function(value) { return regex.test(value); } )
[ 'node.js' ]
>

解决方法

您正在传递对“测试”函数的引用,但是当它被调用时,正则表达式对象将不在其周围.换句话说,在“测试”的内部,这个值将是未定义的.

你可以避免:

items.filter(regex.test.bind(regex))

.bind()方法将返回一个永远以“regex”值运行的函数.

原文地址:https://www.jb51.cc/js/151628.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐