10

*Is there a way to call a function defined inside another function in javaSCRIPT? For example:

window.onload() = function() {
    function my_function(){
        print("Blah");
    };
};

function function_two(){
    my_function();
};

Is there a way to do something like the above (calling my_function in function_two even though it's defined inside the window.onload() function)? In my actual code, which also uses the raphael.js library, I'm trying to write a button in HTML, which using the onClick function, calls a function(like function_two) that runs the function defined in window.onload() (like my_function). However the console says that the my_function is undefined.

tkrishnan
  • 327
  • 3
  • 4
  • 11

3 Answers3

12

The scope of the function is the core issue here, as Zeychin and Trevor have said. I thought I'd offer another way of handling it. Basically, you can set your function to a variable that's in a higher scope (that is, accessible to both the onload and function_two functions), while defining it inside the onload function as you originally have:

var myFunction; //This is the placeholder which sets the scope

window.onload() = function() {
   myFunction = function() { //Assign the function to the myFunction variable
      print('blah');
   }
}

function function_two() {
   myFunction();
}

This might be handy if you only know the information you need for myFunction once you're in the onload event.

Ben Hull
  • 7,524
  • 3
  • 36
  • 56
  • I could not make this example work. It says "JavaScript error: Uncaught TypeError: Property 'myFunction' of object [object Object] is not a function" – Rodrigo De Almeida Siqueira Sep 07 '13 at 13:21
  • Rodrigo - that error suggests you're calling 'myFunction' as a property/method of another object. Can you ask another question or post the code as a JSfiddle? – Ben Hull Sep 09 '13 at 01:30
  • Also, Rodrigo, downvoting an answer in this situation isn't what downvotes are for ... particularly if you want help with your specific problem. Take a look at this (and others like it): http://meta.stackexchange.com/questions/2451/why-do-you-cast-downvotes-on-answers – Ben Hull Sep 09 '13 at 01:38
  • The code is here: http://jsfiddle.net/zEAWk/ It says "Uncaught ReferenceError: Invalid left-hand side in assignment", probably because of the "()" after "window.onload". I also tried to change "print('blah') to "alert('blah')", but was still not able to run. – Rodrigo De Almeida Siqueira Sep 12 '13 at 02:12
3
window.onload = function() {
    my_function()
};

function my_function(){
    alert("Blah");
};

function function_two(){
    my_function();
};
Trevor
  • 11,269
  • 2
  • 33
  • 40
3

You can not do what you are asking to do. The function my_function()'s scope is only within the anonymous function, function(). It falls out of scope when the method is not executing, so this is not possible. Trevor's answer is the way to do this.

Zéychin
  • 4,135
  • 2
  • 28
  • 27