Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2014 (Bloomington, MN) with: Jeff McDowell and Joel Hill and Jonathan Rowny and Shawn Grigson and Jonathan Dowdle and Matt Vickers and Christian Ready and Asher Snyder and Clark Valberg and Oscar Arevalo and David Bainbridge

Calling Sub-Function in Javascript Different in Safari

By Ben Nadel on

I just came across a browser inconsistency that I have never seen before. Granted I am new to this one aspect, but still, interesting. I had an example of code that had a sub function being called in this manner:

  • // This will NOT work in safari.
  • function Foo2(){
  • alert("In Foo2 Method");
  •  
  • (
  • function Bar2(){
  • alert("In Bar2 Method");
  • }
  • )();
  • }
  •  
  • // Call the Foo2 method for testing.
  • Foo2();

In the above example, we have a sub-function that is being called via the notation ( .... )(); This notation is used for nameless functions. In this example the function does have a name, "Foo2." In IE and FireFox, this still works.

If you want to keep this notation and have it work in Safari, you cannot use a function name, as in this example:

  • // This will work in Safari.
  • function Foo(){
  • alert("In Foo Method");
  •  
  • (
  • function (){
  • alert("In Bar Method");
  • }
  • )();
  • }
  • Foo();

In the above example, you will see that the function call is the same ( ... )(); the only difference is that the sub-function is no longer named. It is merely the function definition "function()". This works fine so long as you don't need to refer to the function by name, say as you might in a recursive method call.

In order to recurse, you need the name and you need to change the notation a bit. To use a named function in Safari, you need to call the function explicitly as below:

  • // This will work in Safari.
  • function Foo(){
  • alert("In Foo Method");
  •  
  • function Bar(){
  • alert("In Bar Method");
  • }
  •  
  • Bar();
  • }
  • Foo();

In the above example, you see that we need to call the Bar method explicitly with Bar();. Additionally, we no longer use the ( ... )(); notation and this does work in Safari and the other browsers.


Looking For A New Job?

100% of job board revenue is donated to Kiva. Loans that change livesFind out more »

Reader Comments

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.