Reputation: 39956
Ok, I know what I am doing and I purposely want many multiple scripts like this to be on my page, because these scripts are not supposed to be evaluated on load, however if I set type="something else" then I do not get intellisense and validation which creates trouble while development.
<script type="text/javascript" id="s">
{
// <- following '(' is unexpected
update: function (o){
alert(o);
}
}
</script>
However when I do this, its alright,
<script type="text/javascript" id="s">
{
update: function x(o){
alert(o);
}
}
</script>
Notice the "x" before round brackets. Problem is, if I write "x" then window.x is set to this method and writing multiple scripts creates even further problem.
When I change it to,
<script type="text/javascript" id="s">
{
update: function x(o){
alert("s-update: " + o);
},
method: function x(y){
alert("s-method: " + y);
}
}
</script>
Then I get unexpected token ',' before method
.
,
and if I remove ,
then I get no script error but my code does not get executed, http://jsfiddle.net/2ykdD/1/.Upvotes: 3
Views: 3273
Reputation: 344803
{
indicates the start of a block in JavaScript, as is evident by the following piece of code (which is valid syntax):
{ var hello = "test" }
Internally, this is translated to the following sequence (remembering that variable declarations are hoisted and not block scoped):
{
Ignoring the block, it's equivalent to var hello = "test"
. If we apply this same logic to your code, then
{
// <- following '(' is unexpected
update: function (o){
alert(o);
}
}
is translated to the following sequence:
{
Ignoring the block delimiters, the code is interpreted as:
update: function (o){
alert(o);
}
The reason for the syntax error is that a function statement must have a name. In your second example, the function statement is valid because it has a name. Both function statements have names in the 3rd but the ,
is invalid when following a function statement.
As others have mentioned, the problem is fixed when you wrap the whole thing in braces, because the code becomes an expression and, therefore, legal syntax.
Upvotes: 2
Reputation: 34662
The second statement is valid, because update:
is interpreted as a label, not as a key of an object. You'll have to enclose the anonymous object with parentheses to make it work.
The third is invalid because a misplaced list operator (which ,
is interpreted as in this case).
Upvotes: 2
Reputation: 8220
<script type="text/javascript" id="s">
({
update: function(o){
alert("j-update: " + o);
},
method: function(y){
alert("j-method: " + y);
}
})
</script>
Upvotes: 2
Reputation: 15097
Javascript wants a hint that { ... }
is an expression:
({
update: function x(o){
alert("s-update: " + o);
},
method: function x(y){
alert("s-method: " + y);
}
})
Upvotes: 5