【问题标题】:How do I declare a function inside of another function?如何在另一个函数中声明一个函数?
【发布时间】:2016-03-13 11:01:33
【问题描述】:

如何在另一个函数内部声明一个函数,然后在该函数外部执行?
例子:

function createFunction(){
    function myFunction(){console.log('Hello World!');};
};
createFunction();
myFunction();

这将返回一个错误,指出 myFunction 未定义。
我该如何完成这项工作?

【问题讨论】:

  • 你必须执行createFunction,但它也被闭包隐藏了。你希望完成什么。
  • 首先调用父函数,这样子函数将创建然后调用子函数,但不是这样,而是使用“this”。
  • 你在函数中声明的所有东西都保留在函数中(就像拉斯维加斯)并且在函数之外是未知的(闭包/范围)。你为什么要这样做?
  • 你可以从外部返回内部函数。这样,外部函数的调用会产生内部函数,您可以依次调用它。但是我怀疑你真的需要那个内部函数定义。

标签: javascript


【解决方案1】:

首先你必须执行你的父函数,然后将函数保存在全局命名空间中。这不是好习惯!!但它解决了你的问题。

(function createFunction(){
    window.myFunction = function(){console.log('Hello World!');};
  })();
  myFunction();

【讨论】:

  • 感谢您的帮助,但这对我不起作用
【解决方案2】:

你只需要从你的createFunction返回函数

function createFunction(){
    return function myFunction(){console.log('Hello World!');};
};
var myFunction = createFunction();
myFunction() // => Hello World!, You just learn't functional js

使用函数式 js,您还可以使用 currying 来传递参数,以使函数更具可重用性,例如。

function createFunction( greeting ){
    return function myFunction( who ){console.log( greeting + ' ' + who );};
};
// create two functions from our createFunction and return some partially applied functions.
var hello = createFunction('Hello'); // => myFunction with greeting set
var sup = createFunction('Sup'); // myFunction with greeting set

// now that functions hello and sup have been created use them
hello('World!') // => Hello World!
hello('Internets!') // => Hello Internets!
sup('Stack!') // => Sup Stack!
sup('Functional JS!') // => Sup Functional JS!

【讨论】:

  • 感谢您的回答。我确实返回了这个函数,尽管以另一种方式,而不是你展示的。
猜你喜欢
  • 2012-10-28
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多