【问题标题】:Interesting and strange behaviour of objects and closure in JavascriptJavascript中对象和闭包的有趣和奇怪的行为
【发布时间】:2012-04-26 20:25:24
【问题描述】:
查看代码
<script type = 'text/javascript'>
function a()
{
;
}
a.prototype.hello = function()
{
alert('hello');
}
(function()
{
var b = 8;
}
());
</script>
我没有创建 a 的对象,也没有调用 hello()。但是我正在调用 hello()。
当我删除闭包时,该函数不会自动调用。
IE。对于
<script type = 'text/javascript'>
function a()
{
;
}
a.prototype.hello = function()
{
alert('hello');
}
</script>
这种奇怪行为的原因是什么?
http://jsfiddle.net/6yc9r/
和
http://jsfiddle.net/6yc9r/1/
【问题讨论】:
标签:
javascript
object
closures
prototype
【解决方案1】:
通过省略分号,您会意外调用 hello() 函数。这就是为什么要使用分号的原因,尽管 JS 引擎的自动分号插入功能使它们看起来好像它们不是必需的!试试这个:
<script type = 'text/javascript'>
function a()
{
;
}
a.prototype.hello = function()
{
alert('hello');
};
(function()
{
var b = 8;
}
());
</script>
【解决方案2】:
原因是您缺少;。
因为函数表达式和下一行(之间没有分号,所以第二个函数变成了第一个函数的参数,像这样:
a.prototype.hello = function()
{
alert('hello');
}(function() { ... }());