6

I am looking at code that appears to be declaring a function that would need to be called to run. This function is being declared within an anonymous function. Doesn't this mean that the function will be inaccessible to anything outside of this block?

(function () {
    var _d = vjo.dsf.EventDispatcher;
    var _r = vjo.Registry;

    function $1(p0) {
        return function (event) {
            return this.onSubmit(p0, event);
        };
    };
})();

Why would someone do this? I am not sure of the purpose/relevance of $ in this code.

Nate
  • 919
  • 2
  • 9
  • 18

2 Answers2

10

"Doesn't this mean that the function will be inaccessible to anything outside of this block?"

Yes it does.

"Why would someone do this?"

Usually because it contains code for internal use only, though in your example, the function is never invoked.

"I am not of the purpose/relevance of "$" in this code."

No relevance. Just another valid variable character.

I Hate Lazy
  • 47,415
  • 13
  • 86
  • 77
  • The code example is an extract from a very popular website. Any idea why they would leave this code within their scripts? Also, I'm not sure if this makes a difference but the code has been [beautified](http://jsbeautifier.org/) – Nate Dec 01 '12 at 01:27
  • @Nate: Only thing I could guess would be that the `$1` gets replaced by a server-side code generator on some occasions. Otherwise, I have no idea why they would do this. – I Hate Lazy Dec 01 '12 at 01:54
  • I'm thinking it could possibly be an artefact of the minify'ing process on the scripts. But this seems like a too convenient explanation. – Nate Dec 01 '12 at 01:59
  • @Nate: That could be too. Maybe the minifier uses the `$` in variable names to mark dead code. Just a wild guess. – I Hate Lazy Dec 01 '12 at 02:00
1

The example you posted shows a common pattern of writing "modules" in javascript, although one that has an error. $1 is never invoked and is private, which means it might as well not exist. However, in a valid example, there would be additional code that would call $1 and possibly other functions. Then, when this code was included, the whole thing would evaluate, yet the global namespace would not get polluted with the declarations.

RonaldBarzell
  • 3,822
  • 1
  • 16
  • 23
  • This is what I originally thought but I'm viewing this code from a very popular website. I would not expect them to just throw random pointless code into their scripts. – Nate Dec 01 '12 at 01:20