Interesting and weird object behavior and closure in Javascript

See code

<script type = 'text/javascript'>
function a()
{
    ;
}
a.prototype.hello = function()
{
    alert('hello');
}
(function()
    {
        var b = 8;
    }
());
</script>

I do not create an object a and do not call hello (). But I get a hello () call.

When I remove the closure, the function is not called automatically. i.e. for

<script type = 'text/javascript'>
function a()
{
    ;
}
a.prototype.hello = function()
{
    alert('hello');
}
</script>

What is the reason for this strange behavior?

http://jsfiddle.net/6yc9r/

and
http://jsfiddle.net/6yc9r/1/

+3
source share
2 answers

Omitting the semicolon, you accidentally call the hello () function. That's why using semicolons, even if the automatic semicolon function of JS engines makes them seem like they are not needed! Try the following:

<script type = 'text/javascript'>
function a()
{
    ;
}
a.prototype.hello = function()
{
    alert('hello');
};
(function()
    {
        var b = 8;
    }
());
</script>
+4
source

, ;.

( , , :

a.prototype.hello = function()
{
    alert('hello');
}(function() { ... }());
+3

All Articles