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

Interesting and strange behaviour of objects and closure in Javascript

本文关键字:闭包 Javascript 对象      更新时间:2023-09-26

参见代码

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

我不是在创建 a 的对象,也没有调用 hello()。但是我被调用了hello()。

当我删除闭包时,该函数不会自动调用。即。为

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

这种奇怪行为的原因是什么?

http://jsfiddle.net/6yc9r/


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

通过省略分号,您意外调用了 hello() 函数。这就是为什么使用分号的原因,即使JS引擎的自动分号插入功能使它们看起来没有必要!试试这个:

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

原因是您缺少;

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

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