2012-01-20 54 views
4

换句话说,为什么分号插入失败,导致下面的代码被破坏。为什么关闭分号会破坏这段代码?

function Foo() { } 

Foo.prototype.bar = function() { 
    console.log("bar"); 
} // <------------ missing semicolon 

(function() { 
    Foo.prototype.la = function() { 
     console.log("la"); 
    }; 
})(); 

为什么是JavaScript解析引擎尝试要结合Foo.prototype.bar = function() {什么在我的封闭?有什么我可以在这封闭关系,这将使这个明智吗?

我并不是主张用分号插入可以节省您的期望,我只是想知道为什么(更有用的版本)上面的代码在我意外地离开时破坏了。

回答

3

认为它是这样的...

Foo.prototype.bar = function() { // <-- 1. function 
    console.log("bar"); 
}(function() { // <-- 2. call the 1. function, passing a function argument 
    Foo.prototype.la = function() { 
     console.log("la"); 
    }; 
})(); // <-- 3. tries to invoke the return value of the 1. function, 
     //   but "undefined" was returned. 

我不喜欢使用()为IIFE。我更喜欢其他运营商。

Foo.prototype.bar = function() { 
    console.log("bar"); 
} 

void function() { 
    Foo.prototype.la = function() { 
     console.log("la"); 
    }; 
}(); 

如果我们回到原来的位置,并让第一个函数返回一个函数,您会看到一个函数被调用。

Foo.prototype.bar = function() { // <-- 1. function 

    console.log("bar"); 
    return function() { alert('INVOKED'); }; // 2. return a function 

}(function() { // <-- 3. call the 1. function, passing a function argument 
    Foo.prototype.la = function() { 
     console.log("la"); 
    }; 
})(); // <-- 4. tries to invoke the return value of the 1. function, 
     //   which will now call the returned function with the "alert()" 

更新,可使用一元运算符由@Lasse Reichstein的建议,二元运算符仍然会评估它的左侧和右侧的操作数,并返回结果,这将被用于分配。

+1

是的 - 所以现在bar并没有被赋值,而是被这个函数调用的那个函数的结果。谢谢 –

+0

HEH - 我真的认为我是唯一一个喜欢'+ function()'的人...我认为唯一的其他人是那些缩小器:) –

+0

@AdamRackis:我们有几个人在那里。 :)如果我不关心太多字符,我更喜欢“空白”。似乎更突出。 – 2012-01-20 16:20:32

4

因为它看到(在下面的横线,并采取它的意思是你想呼叫以上(使用下面的函数作为参数)。

+0

*叹* - 说得好,谢谢。 –