簡體   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?

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

您正在傳遞對“test”函數的引用,但是當它被調用時,正則表達式對象將不會出現。 換句話說,里面的“測試”的值, thisundefined

你可以避免這種情況:

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

.bind()方法將返回將始終以“正則表達式”作為價值運行的函數this

您經常無法做到這一點的原因是用作方法的函數不僅僅是方法。 如果您在不調用它們的情況下使用它們,那么它們就會脫離原始上下文。 你可以使用Function.prototype.bind解決這個問題:

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

正如其他人所說,在調用函數引用時, thisundefined的。 我想提供一種非反身的,略顯冗長的替代方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM