简体   繁体   中英

Uncaught Syntax error: unexpected token ( even though function is valid

I am trying to make a web application. I have a task controller in a separate .js file which I include in the main .html file:

<head>
  <script src = "tasks-controller.js"></script>
</head>

and the file tasks-controller.js:

tasksController = function() {
    var taskPage;
    var initialized = false;

    return
    {
        init: function(page) {
            if(!initialized)
            {
                 .... some manipulation with jQuery...    
                initialized = true;             
            }
        }
    }
} ();

Back in my main .html file I call tasks controller right after body closing element:

<script>
$(document).ready(function()
{
  tasksController.init($('#taskPage'));
}
</script>

When I test the file, in Google chrome tools, I get Uncaught SyntaxError: Unexpected token ( on line 8 of tasks-controller.js which is this line:

init: function(page)

along with another error that 'tasksController' is not defined when I call it above. Any suggestions to what I am doing wrong? Thanks!

The ready method is where the error is. You missed the ) of ready .

See the highlighted code and comments in the code below.

$(document).ready(function() {
    tasksController.init($('#taskPage'));
}); // The ) you've missed
// ^^^

Other problem in your code is the return statement. If you put the object to the next line of return it will always return undefined . Automatic semicolon insertion will cause the code to put semicolon after return .

So, it'll be like return; .

Use following code:

tasksController = function() {
    var taskPage;
    var initialized = false;

    return {
        init: function(page) {
            if (!initialized) {
                ....some manipulation with jQuery...
                initialized = true;
            }
        }
    };
}();

Due to implicit semicolons, your code equals this:

return;
{
    init: function(page) {
        if(!initialized)
        {
             .... some manipulation with jQuery...    
            initialized = true;             
        }
    }
}

The return is returning nothing, and so the {} makes a new block. Now you can see why you have a syntax error.

Just change the first line to return { (no newline) and you should be good.

See Strangest language feature .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM