JS函数返回函数供以后使用 - 参数undefined

时间:2016-03-30 18:01:59

标签: javascript function

我正在尝试创建一个函数,然后可以根据输入返回许多函数。这是我面临的问题的一个例子。

var giveFunction = function(text) {
    return function(text) {
        console.log(text)
    }
}
var test = giveFunction('this is a test');
test()

最后运行test()打印undefined而不是'这是一个测试。'有没有解决这个问题的方法?

2 个答案:

答案 0 :(得分:4)

内部函数不应包含任何参数

var giveFunction = function(text) {
    return function() {
        console.log(text)
    }
}

让它创建一个闭包。如果它有一个参数,则会在执行期间读取该参数,并且会打印undefined,因为您没有使用任何参数调用该函数。

如果您希望代码正常运行,那么您必须使用bind

var giveFunction = function(text) {
    return function(text) {
        console.log(text)
    }.bind(null, text)
}
var test = giveFunction('this is a test');
test();  //'this is a test'

答案 1 :(得分:1)

让我们更进一步,问为什么?

var outerFunction = function(outerParameter) {
   return innerFunction function(innerParameter) {
     // in here we have access to anything in this function and the outer function
     // all the way to out the the global scope
     // therefore, we dont need to pass innerParameter in again as a parameter! ( in your case we 'next')
   }
  /// now over here, outside of innerFunction, we do NOT have access to innerParameter!
}

因此,将上述原则应用于您的代码:

var giveFunction = function(text) {
    return function() {
        console.log(text)
    }
}
var test = giveFunction('this is a test');
test()

现在有效!

最后,查看javascript标记下最热门的帖子: How do JavaScript closures work?