Andrew
Andrew

Reputation: 3673

Anonymous Function Causing Problems

The only thing that is giving me problems is executing an anonymous function call. I even made an empty call to see if there was problems with the code inside; that isn't the case.

This is the format I write them in:

(function(){})(); 

I'm positive that that is correct and standard use, but it keeps throwing this error:

Uncaught TypeError: (intermediate value)(intermediate value)(...) is not a function(anonymous function)

The error can be found HERE while the site is running.

the code excerpt above is no different than what's in my program

Upvotes: 4

Views: 3466

Answers (2)

Oriol
Oriol

Reputation: 288710

Maybe you have something like

(function() { return 123; })
(function(){})();

It becomes

(123)();

But 123 is not a function. So it throws

TypeError: (intermediate value)(...) is not a function

To fix it, add a semi-colon:

(function() { return 123; }); // <-- semi-colon
(function(){})(); // No error

Note the semi-colon is needed in function expressions, but not necessary in function declarations:

function foo() {} // No semi-colon
(function(){})(); // No error

Upvotes: 4

user2357112
user2357112

Reputation: 282138

The code giving you trouble is

    ctrl.deleteObject = function(obj){
        var index = ctrl.objects.indexOf(obj);
        if( index > -1 ){
            this.objects.splice(index, 1);
        }
    }
    //}


    // //START GAME
     (function(){
     //ctrl.createObject(new PlayerPaddle(50, 50));
        //ctrl.init();
    })();

Stripping out comments, we get

    ctrl.deleteObject = function(obj){
        var index = ctrl.objects.indexOf(obj);
        if( index > -1 ){
            this.objects.splice(index, 1);
        }
    }
     (function(){
    })();

The assignment to ctrl.deleteObject is not terminated by a semicolon, and the parentheses on the next line look like a valid continuation of the assignment, so Javascript doesn't insert a semicolon for you. Instead of an assignment and an anonymous function call, you end up calling the function you were trying to assign to ctrl.deleteObject, and then calling its return value, which isn't a function.

Upvotes: 8

Related Questions