私有成员(使用闭包),为什么初始化后添加的函数不能访问私有成员?

Javascript: Private Members (using closure), why can't functions added after initialization access private members?

本文关键字:成员 添加 函数 访问 不能 闭包 为什么 初始化      更新时间:2023-09-26
 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"

现在,这种行为可能是一件好事。但它打破了我对结束的直觉。匿名"私有函数和返回对象之间的链接不是吗?当我添加setKey不是然后返回对象(测试)的一部分?

事先感谢您提供的任何帮助

可以这样考虑:闭包是对当前作用域链的引用。只有引用相同作用域的东西才会修改相同的变量。本节是key变量存在的作用域:

{var key = 200; 
  return {getKey : function(){return key} };          
 }

你的set函数定义在这个作用域之外,因此修改了一个名为key的不同变量。闭包和作用域不连接到对象。如果希望以后能够添加set函数,则需要使该变量成为对象的实际成员:

test = (function(){
  return {key: 200, getKey : function(){return this.key} };          
 })();
test.getKey() //returns 200, so far so good
test.setKey = function(arg){this.key = arg};
test.setKey(400);
test.getKey() //returns 400