-2

How do I declare a function inside of another function, and then execute outside of that function?
Example:

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

This will return an error saying, that myFunction is not defined.
How do I make this work?

  • you have to execute `createFunction`, but its hidden by closures as well. what are you hoping to accomplish. – Daniel A. White Dec 08 '15 at 13:41
  • 1
    First call the parent function so child function will create then call the child function but not like this but use "this". – Leo the lion Dec 08 '15 at 13:42
  • all the thing you declare in the function stay in the function (it's like las vegas) and are unknow outside the function (closure/scope). why you want to do this ? – AlainIb Dec 08 '15 at 13:44
  • You could return the inner function from the outer one. That way, a invocation of the outer function produces the inner function, which you can call in its turn. However I doubt you really need that inner function definition to begin with. – Aaron Dec 08 '15 at 13:46
  • See http://stackoverflow.com/questions/7295634/javascript-nested-function – Krii Dec 08 '15 at 13:49
  • This is just an example, in my actual script, I want to check, what the user has chosen, when a dropdown has changed it's value, then create a function appropiate to the user's choice. – Christian L.W. Dec 09 '15 at 13:28

2 Answers2

1

At first you have to execute your parent function, and then save function in global namespace. It's not good practice!! But it solves your problem.

(function createFunction(){
    window.myFunction = function(){console.log('Hello World!');};
  })();
  myFunction();
Sergei Stralenia
  • 855
  • 7
  • 16
1

You just need to return the function from your createFunction

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

with functional js you can also use currying to pass in parameters to make functions more re-usable eg.

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!
synthet1c
  • 6,152
  • 2
  • 24
  • 39