【发布时间】:2014-05-15 12:16:53
【问题描述】:
test = (function(){var key = 200;
return {getKey : function(){return key} };
})();
test.getKey() //returns 200, so far so good
test.setKey() = function(arg){key = arg};
test.setKey(400);
test.getKey() //still returns 200, setKey cannot access the private member "key"
现在,这种行为可能是件好事。但这打破了我对闭包如何工作的直觉。匿名“private”函数和返回对象之间的链接不是吗?当我添加 setKey 时,它不是返回对象(测试)的一部分吗?
提前感谢您提供的任何帮助。
【问题讨论】:
-
变量属于进入该上下文时创建的执行上下文,以后无法添加。
标签: javascript closures private