totally new to JS so please forgive if this is mind-bogglingly obvious.
这对JS来说是全新的,所以请原谅,如果这太明显了。
Suppose I want to filter a list of strings with a function f that maps string -> bool. This works:
假设我要用一个函数f来过滤一个字符串列表,这个函数映射字符串-> bool。如此:
filteredList = list.filter(function(x) { return f(x); })
This fails:
这个操作失败:
filteredList = list.filter(f)
Why???
为什么? ? ?
Code example:
代码示例:
~/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' ]
>
2 个解决方案
#1
17
You're passing a reference to the "test" function, but when it gets called the regular expression object won't be around. In other words, inside "test" the value of this
will be undefined
.
您正在传递一个对“测试”函数的引用,但是当它被调用时,正则表达式对象就不存在了。换句话说,在“测试”内部,这个值将是不确定的。
You can avoid that:
你可以避免:
items.filter(regex.test.bind(regex))
The .bind()
method will return a function that'll always run with the value of "regex" as this
.
bind()方法将返回一个函数,该函数将始终以“regex”的值运行。
#2
4
The reason you often can't do this is that functions used as methods are not simply methods. If you use them without invoking them as methods they are then divorced of their original context. You can get around this with Function.prototype.bind
:
不能这样做的原因是作为方法使用的函数不是简单的方法。如果您使用它们而不将它们作为方法调用,那么它们将与原始上下文分离。你可以用function。prototype.bind:
items.filter(regex.test.bind(regex));
#1
17
You're passing a reference to the "test" function, but when it gets called the regular expression object won't be around. In other words, inside "test" the value of this
will be undefined
.
您正在传递一个对“测试”函数的引用,但是当它被调用时,正则表达式对象就不存在了。换句话说,在“测试”内部,这个值将是不确定的。
You can avoid that:
你可以避免:
items.filter(regex.test.bind(regex))
The .bind()
method will return a function that'll always run with the value of "regex" as this
.
bind()方法将返回一个函数,该函数将始终以“regex”的值运行。
#2
4
The reason you often can't do this is that functions used as methods are not simply methods. If you use them without invoking them as methods they are then divorced of their original context. You can get around this with Function.prototype.bind
:
不能这样做的原因是作为方法使用的函数不是简单的方法。如果您使用它们而不将它们作为方法调用,那么它们将与原始上下文分离。你可以用function。prototype.bind:
items.filter(regex.test.bind(regex));