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.
- I want to know how can I create just an JavaScript Object Notation which will be executed later on by giving ids. See working code at http://jsfiddle.net/MDJbT/, but I do get a script error if I include
,and if I remove,then I get no script error but my code does not get executed, http://jsfiddle.net/2ykdD/1/. - I need this in a framework which will allow us to write scripts in completely “id” independent way, so that there will not be any conflict of global methods. Both scripts have same names, but different logic. The only difference is the “id”, I know which ID to refer and which method to call.
- This is very small part of complicated framework where ids are automatically assigned and methods are part of class hierarchy which is dynamically set in runtime, preserving scope.
- I do not want these scripts to be executed at all.
- I want these scripts to be written in such way so that Visual Studio and other editors will precisely show intellisense and give errors about syntax etc.
- I will execute these scripts only on action invoked by user within an eval scope by providing further method arguements.
{indicates the start of a block in JavaScript, as is evident by the following piece of code (which is valid syntax):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, thenis translated to the following sequence:
{Ignoring the block delimiters, the code is interpreted as:
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.