-1

I try to write a javascript Self-Executing Anonymous Function

window.App = window.App || {}

    (function (global) {
        global.test = function () {
            console.log('test');
        }
    })(App);

$(function () {
    App.test();
})

but the fire bug tell me: ({}) is not a function

then I try move the (app) in, like:

(function (global) {
    global.test = function () {
        console.log('test');
    }
}(App));

then the firebug tell me :

App is not defined

So wht's wrong with my code?How can I do it in right way?

here is the demo

hh54188
  • 14,887
  • 32
  • 113
  • 184
  • This code looks a little strange to me so I won't provide an answer, but shouldn't there be some code between the curly braces on the first line? – Jezen Thomas Jun 25 '12 at 08:08
  • @JezenThomas no, the {} is just a way of creating an empty object. You can see it gets passed into the function as *global*, where it gets a method *test* defined on it. – McGarnagle Jun 25 '12 at 08:13
  • That is a nice example for problems with semicolon insertion in the wild. Kids, never forget your semicolons! – kioopi Jun 25 '12 at 08:14
  • Very interesting. Great question; not sure why it's been downvoted. +1 – Jezen Thomas Jun 25 '12 at 08:24

2 Answers2

7

Try this:

window.App = window.App || {};

You are missing a semicolon there!

Amberlamps
  • 39,180
  • 5
  • 43
  • 53
1

Add a semicolon to your first row

window.App = window.App || {};

JS thought that that the parentheses on row 3 was part of your new empty object on row 1.

Attila Szeremi
  • 5,235
  • 5
  • 40
  • 64