对JS来说是全新的,请原谅,如果这是令人难以置信的显而易见的话.
假设我想过滤一个字符串列表,其函数为f,映射字符串 - > bool.这有效:
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.(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' ] >
Pointy.. 19
您正在传递对"test"函数的引用,但是当它被调用时,正则表达式对象将不会出现.换句话说,内部"测试"的值this
将是undefined
.
你可以避免这种情况:
items.filter(regex.test.bind(regex))
该.bind()
方法将返回一个总是以"regex"的值运行的函数this
.
您正在传递对"test"函数的引用,但是当它被调用时,正则表达式对象将不会出现.换句话说,内部"测试"的值this
将是undefined
.
你可以避免这种情况:
items.filter(regex.test.bind(regex))
该.bind()
方法将返回一个总是以"regex"的值运行的函数this
.
您经常无法做到这一点的原因是用作方法的函数不仅仅是方法.如果您在不调用它们的情况下使用它们,那么它们就会脱离原始上下文.你可以解决这个问题Function.prototype.bind
:
items.filter(regex.test.bind(regex));