【发布时间】:2014-10-06 09:39:59
【问题描述】:
我试图理解 js 闭包的属性之一: 参考来自Closures store references to the outer function’s variables
function myId()
{
var userID=999;
return
{
getId: function() {
return userID;
},
setId: function(newId) {
userID = newId;
}
};
}
var callInnerFun = myId();
console.log(callInnerFun.getId());
callInnerFun.setId(500);
console.log(callInnerFun.getId());
当我尝试在 Node 甚至浏览器上运行上述代码时,我收到以下错误:
SyntaxError: function statement requires a name at getId: function() {
我尝试过但未能理解我真正错过了什么。是语法错误,还是与我的文本编辑器 sublime text 有关,因为如果我尝试运行与从上面给出的链接复制的完全相同的代码,那么一切正常。
而在我的代码(上面)中,逻辑仍然与引用相同,只是缩进和变量名称发生了变化。是改变这些破坏了我的代码吗?
【问题讨论】:
-
错字:
getIdfunction后面有一个额外的}。另外,returnstatements don't allow line-breaks between the keyword and the value expression。然而,对象文字/初始化器允许在{之后使用它们。 -
错误是因为
{...}被解析为单独的语句,作为 block 而不是对象文字;getId:作为 label 而不是键;和function作为declaration,它需要一个名称,而不是expression。
标签: javascript node.js closures