3

I have downloaded an external JavaScript file and want to create a HTML5 User Interface for it. I don't understand why the JavaScript code (see bellow) initiates his main function like that.

//JavaScript Code
(function(Raphael) {
      // some codes here
})(window.Raphael);

Why is that function between parentheses?

What does the "window.Raphael" mean?

Cœur
  • 37,241
  • 25
  • 195
  • 267

2 Answers2

4

This is an example of a self invoking anonymous function.

You are passing in window.Raphael into this function which is essentially "renamed" to Raphael inside the function.

Community
  • 1
  • 1
Undefined
  • 11,234
  • 5
  • 37
  • 62
  • 1
    theoritically it is incorrect to call it *self-invoking* since it is not the function that is calling itself. Instead it is the thread (could be another function or global scope) it is defined in. – techfoobar Mar 11 '13 at 16:05
  • 1
    And the reason for this is most likely so that a minification tool then could shorten all uses of `Raphael` to a much shorter variable name within that function, without breaking the code. – Christofer Eliasson Mar 11 '13 at 16:05
-1

That is an immediately executing function (IIFE). Meaning one thats defined and executed immediately afterwards.

In this case, its also using RaphaelJS which is an SVG library. The IIFE accepts a global variable presumably defined by Raphael that is accessible at window.Raphael

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • 1
    downvoted because IEF is YAUA (Yet Another Unnecessary Acronym). –  Mar 11 '13 at 16:03
  • Agreed. I just didn't want to keep typing "immediately executing function" again and again.. :-) – techfoobar Mar 11 '13 at 16:04
  • Just for arguments sake the most common acronym is IIFE - immediately-invoked function expression. – Adam Jenkins Mar 11 '13 at 16:05
  • @Adam - Right, thats what i intended. – techfoobar Mar 11 '13 at 16:06
  • I've never seen that acronym, seems to be something you only see in JavaScript. Other languages that can do this don't ever define the acronym since it's a normal course of action. –  Mar 11 '13 at 16:09