简体   繁体   English

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

[英]Why do I need to write “function(value) {return my_function(value);}” as a callback in node.js?

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. 假设我想过滤一个字符串列表,其函数为f,映射字符串 - > bool。 This works: 这有效:

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' ]
> 

You're passing a reference to the "test" function, but when it gets called the regular expression object won't be around. 您正在传递对“test”函数的引用,但是当它被调用时,正则表达式对象将不会出现。 In other words, inside "test" the value of this will be undefined . 换句话说,里面的“测试”的值, thisundefined

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()方法将返回将始终以“正则表达式”作为价值运行的函数this

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

As others have said, this is undefined when the function reference is called. 正如其他人所说,在调用函数引用时, thisundefined的。 I'd like to offer a non-reflexive, slightly verbose, alternative: 我想提供一种非反身的,略显冗长的替代方案:

items.filter(RegExp.prototype.test.bind(/regex/g));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM