0

Can some help on to read the variables inside the closures. I know by having a function with return statement i can get the value.

var getCounter = (function () {
    var counter = 10;
    return function () {return counter;}
})();

getCounter(); produces 10

Is there any way to access or read the variable without the return function ?

5
  • 1
    no... that is the whole purpose of closure variables Commented Apr 7, 2016 at 6:13
  • 1
    why do you want to do that Commented Apr 7, 2016 at 6:13
  • You can but why do you it ? Why have you introduced closure then ? Commented Apr 7, 2016 at 6:16
  • @RayonDabre, Just curious about to get the value in one our test cases. Also we are following best practices to go with closures for our work. Commented Apr 7, 2016 at 6:19
  • You can certainly define it global..But value will be updated if closure manipulates it.. Commented Apr 7, 2016 at 6:20

3 Answers 3

1
var getCounter = (function () {
    this.counter = 10;
})();

console.log(counter);

or

var getCounter = (function () {
        counter = 10;
    })();

    console.log(counter);

jsfiddle

Sign up to request clarification or add additional context in comments.

3 Comments

Well in this case, this belongs to window.. if OP wants to do it this way, then why closure ? Also note, this will fail in "use strict";
var getCounter = (function () { this.counter = 10; })(); This code will also produce the same result what is purpose writing return function () {return counter;} as getCounter is self-executing function where this refers to window.
then ...dont use closure..Its close the purpose of the closure....or simply use counter...
0

I dont know why you need a closure here,

var getCounter = (function () {
  counter = 10;
  return counter;
})();
// As you wrote a closure it is self executed so getCounter variable has the counter value; 
var x = getCounter; 

Comments

0

You can also try this,

var counter;
var getCounter = (function() {
  counter = 10;
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.