Manipulate a variable defined in a closure

Say I have a Javascript class defined and created this way:

Demo = function() { var abc = "foo"; return { get test() { return abc; } } } obj = Demo(); obj.test // evaluates to "foo" 

Opposing only this demo instance of obj , can I change the value of the variable abc that belongs to this object, which was defined in the closure introduced by the constructor function?

+4
source share
3 answers

var abc NOT available directly outside of the demo.

If you want to change it from outside this area, you need to add a method to install it.

 Demo = function() { var abc = "foo"; return { get test() { return abc; } } this.setTest(a) {abc = a;} } var obj = new Demo(); obj.setTest("fun"); 

See this previous discussion for examples of the types of accessories you could use.

+3
source

No. This is one of the basic uses for closing - to define private, inaccessible variables. They can be restored, but if there is a "setter" function, they cannot be changed.

+2
source

I think you are a little confused. If you use Demo as a class, you do not want to call it as a function, but rather as an instance.

When used with instantiation, you can do this:

 function Demo(){ var abc = "some value"; this.setAbc = function(val){ return abc = val; } this.getAbc = function(){ return abc; } } var d = new Demo(); d.getAbc() // => 'some value'; d.setAbc('another value'); d.getAbc() // => 'another value'; 

These types of functions (defined in the "constructor") are called privileged functions. They have access to both public (i.e. defined on the prototype) and private variables. Read this for a good cut for public / private / privileged class members.

note that if you just do:

 var d = Demo(); 

You are not getting an instance of Demo, you are just getting what it returns. In my case, undefined .

change

After reading your message again, the quick reply will be NO, and not with your specific definition, you will need to do something like what I am doing.

OR if you stick to your paradigm:

 function Demo(){ var abc = "some value"; return { get test(){ return abc; }, set test(val){ abc = val; } } } 
0
source

All Articles