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

StackOverflow https://stackoverflow.com/questions/23677972

  •  23-07-2023
  •  | 
  •  

Domanda

 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"

Now, this behavior is probably a good thing. But it break my intuition for how closure works. Isn't the link between the anonymous "private function and the return object? When I add setKey isn't it then part of the returned object (test)?

Thanks in advance for any help you can provide.

È stato utile?

Soluzione

Think of it this way: A closure is a reference to the current scope chain. Only something which references the same scope will be modifying the same variable. This section is the scope in which the key variable exists:

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

Your set function is defined outside this scope and thus modifies a different variable named key. Closures and scopes are not connected to objects. If you wanted to be able to add the set function later, you would need to make the variable an actual member of the object:

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top