Javascript中对象和闭包的有趣而奇怪的行为

Javascript中对象和闭包的有趣而奇怪的行为,javascript,object,closures,prototype,Javascript,Object,Closures,Prototype,参见代码 <script type = 'text/javascript'> function a() { ; } a.prototype.hello = function() { alert('hello'); } (function() { var b = 8; } ()); </script>​ 函数a() { ; } a、 prototype.hello=function() { 警惕(“你好”); } (功能(

参见代码

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

函数a()
{
;
}
a、 prototype.hello=function()
{
警惕(“你好”);
}
(功能()
{
var b=8;
}
());
​
我不是在创建一个对象,也不是在调用hello(),而是在调用hello()

当我移除闭包时,函数不会自动调用。 例如


函数a()
{
;
}
a、 prototype.hello=function()
{
警惕(“你好”);
}
这种奇怪行为的原因是什么



原因是您缺少一个

因为函数表达式和下一行的
)之间没有分号,所以第二个函数成为第一个函数的参数,如下所示:

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

通过省略分号,您无意中调用了hello()函数。这就是为什么要使用分号,尽管JS引擎的自动分号插入功能使它们看起来不必要!尝试以下操作:

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

函数a()
{
;
}
a、 prototype.hello=function()
{
警惕(“你好”);
};
(功能()
{
var b=8;
}
());
​
<script type = 'text/javascript'>
function a()
{
    ;
}
a.prototype.hello = function()
{
    alert('hello');
};
(function()
    {
        var b = 8;
    }
());
</script>​