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

 啊咧咧咧咧咧咧咧列 发布于 2023-02-10 14:53

对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.

2 个回答
  • 您正在传递对"test"函数的引用,但是当它被调用时,正则表达式对象将不会出现.换句话说,内部"测试"的值this将是undefined.

    你可以避免这种情况:

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

    .bind()方法将返回一个总是以"regex"的值运行的函数this.

    2023-02-10 14:55 回答
  • 您经常无法做到这一点的原因是用作方法的函数不仅仅是方法.如果您在不调用它们的情况下使用它们,那么它们就会脱离原始上下文.你可以解决这个问题Function.prototype.bind:

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

    2023-02-10 14:56 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有