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

3

查看代码

<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/

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


2个回答

4

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

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

3
原因是你漏了一个分号。
由于函数表达式和下一行的 ( 之间没有分号,第二个函数就成为第一个函数的参数,如下所示:
a.prototype.hello = function()
{
    alert('hello');
}(function() { ... }());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接