简体   繁体   English

外部函数返回内部函数,可以从外部函数访问值

[英]Outer function returns an inner function with access to values from outer function

I need to create a function which I will pass to my database server. 我需要创建一个函数,该函数将传递给数据库服务器。 The returned function will take a single item as a parameter and compare that item to a list of requirements. 返回的函数将单个项目作为参数,并将该项目与需求列表进行比较。

For this I need a function generating function that takes an array as it's argument and returns the inner function which has that array built in to it. 为此,我需要一个函数生成函数,该函数将数组作为参数,并返回内置该数组的内部函数。

Here's an example: 这是一个例子:

function create_query (list_of_requirements) {
  return function (item) {
    var is_match = true
    // the next function sets is_match to false if the item fails
    list_of_requirements.forEach(check_if_item_meets_requirement)
    return is_match
  }
}

An example of using this: 使用此示例:

function search (parsed_user_string) {
  db.get(create_query(parsed_user_string)).then(function(results){
    show_results(results)
  })
}

How can I build the list of requirements into the inner function? 如何将需求列表构建到内部函数中?

I needed to use a closure. 我需要使用闭包。

Here's a simpler example of a solution. 这是解决方案的一个简单示例。

function makePrinter (num) {
  (return function () {
    print(num)
    })
}

and then: 接着:

var print5 = makePrinter(5)
print5() > prints 5!

I still don't quite get how closures accomplish this, but there it is. 我仍然不太了解闭包如何完成此任务,但确实如此。

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

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