Javascript weird syntax
So I was programming some stuff in Javascript and some time later I saw I made a typo in the following piece of code:
(function() {
var someEl = document.getElementById('id-of-some-el'),l <-----
someOtherEl = document.getElementById('some-other-el');
someEl.onclick = function() {
...
};
})();
Notice how the l
isn't supposed to be there. I've only tested this in Firefox but, why didn't I get a syntax erro开发者_开发知识库r?
You were trying to create two variables inside the var
-statement:
var someEl = document.getElementById('id-of-some-el'),
someOtherEl = document.getElementById('some-other-el');
The introduction of the comma meant that you created someEl
and l
:
var someEl = document.getElementById('id-of-some-el'),l
Semicolons at the end of JS lines are optional, so now you have a distinct, second line of code afterwards:
someOtherEl = document.getElementById('some-other-el');
And this is valid because you can assign to variables without explicitly var
-ing them (albeit imbuing slightly different semantics to your program).
since ending lines with semi colons is not mandatory this code is being evaluated like this:
var someEl = document.getElementById('id-of-some-el'), l;
someOtherEl = document.getElementById('some-other-el');
It is valid since semicolons are not mandatory.
someEl
and l
would be local variables
someOtherEl
would be global since it now has no var
l
would be undefined.
Use console/alert to see it.
var a,b,c;
alert(a);
You've accidentally created three variables: someEl
, l
and someOtherEl
The new line denotes a new statement in this instance.
If you put them all on the same line, eg:
var someEl = document.getElementById('id-of-some-el'),l someOtherEl = document.getElementById('some-other-el');
you'd get Syntax Error: Unexpected identifier
, as you expected.
This is equal to
var someEl = document.getElementById('id-of-some-el');
var l;
someOtherEl = document.getElementById('some-other-el');
Which is not really a syntax error in stricter languages either, but it would perhaps give a warning about an unused variable in compiled languages.
JavaScript is very forgiving, which can sometimes give some interesting debugging sessions as it happily accepts a undefined variable (that may were a typo for another variable) suddenly appearing anywhere.
Although the code you've written is technically valid, JSLint will report it as a warning.
Problem at line 1 character 56: Expected ';' and instead saw 'someOtherEl'.
var someEl = document.getElementById('id-of-some-el'),l
Problem at line 2 character 9: 'someOtherEl' was used before it was defined.
someOtherEl = document.getElementById('some-other-el');
精彩评论