Javascript 如何在另一个函数中声明一个函数?

Javascript 如何在另一个函数中声明一个函数?,javascript,Javascript,如何在另一个函数内部声明一个函数,然后在该函数外部执行? 例子: 这将返回一个错误,说明myFunction未定义。 如何使其工作?首先必须执行父函数,然后将函数保存在全局命名空间中。这不是个好习惯!!但它解决了你的问题 (function createFunction(){ window.myFunction = function(){console.log('Hello World!');}; })(); myFunction(); 您只需从createFunction

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

这将返回一个错误,说明myFunction未定义。

如何使其工作?

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

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

您只需从
createFunction

function createFunction(){
    return function myFunction(){console.log('Hello World!');};
};
var myFunction = createFunction();
myFunction() // => Hello World!, You just learn't functional js
使用functional 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!

您必须执行
createFunction
,但它也被闭包隐藏。您希望实现什么。首先调用父函数,以便子函数将创建,然后调用子函数,但不要像这样,而是使用“this”。您在函数中声明的所有内容都保留在函数中(就像拉斯维加斯),并且在函数外未知(闭包/范围)。为什么要这样做?可以从外部函数返回内部函数。这样,外部函数的调用将生成内部函数,您可以依次调用内部函数。不过我怀疑你是否真的需要从内部函数定义开始。谢谢你的帮助,但这对我来说并不管用。我确实返回了这个函数,不过是以另一种方式返回的,比您显示的要多。
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!