Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate variable defined in closure

Say I have a Javascript class defined and instantiated like this:

Demo = function() { 
  var abc = "foo";

  return {
    get test() { return abc; }
  }
}

obj = Demo();
obj.test  // evaluates to "foo"

Confronted only with this Demo instance obj, can I change the value of the variable abc belonging to this object, that was defined in the closure introduced by the constructur function?

like image 433
Niklas B. Avatar asked Sep 06 '11 21:09

Niklas B.


People also ask

What is a closure variable?

A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created.

What is a closure variable in R?

Closures are used for creating functions within a function in the R environment. These are useful when the functions are changing/ repeating in the code with the same dataset.

Where are closure variables stored?

The Complete Full-Stack JavaScript Course! A closure function gives access to the scope of an outer function from an inner function. It also allows private variables. Closure variables are stored in stack and heap.

What are closures few common uses for closures?

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.


2 Answers

var abc is NOT directly available outside the scope of Demo.

If you want to change it from outside that scope, you have to add a method to set 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 accessors you could use.

like image 81
jfriend00 Avatar answered Sep 29 '22 17:09

jfriend00


No. This is one of the base uses for a closure - to define private, inaccessible variables. They can be retrieved, but unless there is a "setter" function, they cannot be modified.

like image 44
g.d.d.c Avatar answered Sep 29 '22 17:09

g.d.d.c