yigal
yigal

Reputation: 4715

Print the variables of js closure?

here is my js code

function counter(count){
  function get(){
    return count
  }
  function inc(){
    count++;
  }
  function dec(){
    count--;
  }  
  return {dec,inc}
}
const the_counter=counter(10)
the_counter.inc()
console.log(the_counter)

my question is: how do I printout the variables of closure without changing the closure code. I tried console.log, but is does not printout the value of count

Upvotes: 0

Views: 423

Answers (1)

Bergi
Bergi

Reputation: 664346

How do I access the variables of closure without changing the closure code?

This is impossible. Closed-over variables are private.

I am looking for some generic way to dump all of the closure variable without having to write anything to achieve that.

There is none. At least not for accessing the variable and passing it to console.log to print it.

However, the object your code did log can be inspected in the console (or in the debugger) and you can navigate to the closure scope:

Chromium devtools screenshot

Upvotes: 2

Related Questions