NOTE: originally, I thought the issue was caused by something more complex; I see now (and edited the title and sample code) that the only difference is the presence or absence of a semicolon. That may make this a no-brainer to answer, but I was still surprised to see a trailing semicolon matters in this case and not others...
Why does this work:
<script type="text/javascript">
this.someFunc = function () {};
(function () {
console.log("self-invoking function called.")
})();
</script>
but this does not:
<script type="text/javascript">
this.someFunc = function () {}
(function () {
console.log("self-invoking functio开发者_如何转开发n called.")
})();
</script>
and yet, this does:
<script type="text/javascript">
this.someFunc = function () {}
var someVar = "value";
console.log("someVar is:"+someVar);
</script>
The latter interprets the self-invoking function as undefined
, and therefore cannot evaluate/execute it. Tested on Chrome 13, Firefox 6, and Safari 5 on OSX.
I believe the second snippet is actually executing the empty function declaration. If you change your example to this:
<script type="text/javascript">
this.someFunc = function (arg) { console.log(arg); }
(function () {
console.log("self-invoking function called.")
})();
</script>
and then run (FF6), you will see that it logs: function()
. It's passing in the second anonymous function as an argument for the first. This makes more sense if you rearrange:
<script type="text/javascript">
this.someFunc = function (arg) { console.log(arg); }(
function () {
console.log("self-invoking function called.")
})
(); //the parser doesn't know what to do with this line.
</script>
Just looking at the first Related topic on the right of your question: Why should I use a semicolon after every function in javascript?
The accepted answer is a great explanation of this behavior.
精彩评论