JavaScript中“return”语句的奇怪行为
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了JavaScript中“return”语句的奇怪行为,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1900字,纯文字阅读大概需要3分钟。
内容图文
参见英文答案 > Why do results vary based on curly brace placement? 6个
我是JavaScript的新手,刚开始用JavaScript进行一些更严肃的开发.我有很多乐趣来实现Module模式.真正让我发疯的一件事是“回归”陈述的行为.如果你写的话,这是一个很大的不同
Test = ( function()
{
var message = "Hello World!";
return
{
// Does not work
printTest: function() { window.alert(message); }
};
}());
要么
Test = ( function()
{
var message = "Hello World!";
return {
// Works well
printTest: function() { window.alert(message); }
};
}());
请注意’return’语句后的花括号.
这是一个典型的愚蠢的菜鸟错误,并在某处有详细记录吗?
萤火虫无法给出一丝暗示. IE9和Chrome确实在代码的后面位置报告了一些模糊的语法错误:“printTest:function()”中’function’语句之后的左大括号.
对此有何评论? JavaScript中有更多这样的陷阱吗?
解决方法:
如果将括号放到下一行,则解释器会假定存在分号.
所以你的return语句将被解释为:
return;
{
printTest: function() { window.alert(message); };
}
如果我记得很清楚,我会在JavaScript中解决这个问题:好的部分
A.3.分号插入
JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do
not depend on this. It can mask more serious errors.
It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of
semicolon insertion on the return statement. If a return statement returns a value, that value expression
must begin on the same line as the return:
return
{
status: true
};
This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it
into a statement that returns undefined. There is no warning that semicolon insertion caused the
misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line
and not at the beginning of the next line:
return {
status: true
};
“JavaScript:道格拉斯克罗克福德的好零件.版权所有2008 Yahoo! Inc.,
978-0-596-51774-8“.
内容总结
以上是互联网集市为您收集整理的JavaScript中“return”语句的奇怪行为全部内容,希望文章能够帮你解决JavaScript中“return”语句的奇怪行为所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。