Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clever way to access a variable inside a wrapped function?

Tags:

javascript

var x=(function(){var u=1;})();

console.log(x.u); // undefined

Is there any way at all to ether get, access or eventually console.log u?

Is there any code I could put inside x that might make u vulnerable / accessable from the outside?

Edit: I mean without returning u "directly". Is there any way of accidentally exposing u?

like image 450
8DK Avatar asked Jun 29 '14 12:06

8DK


People also ask

Can you access variables inside a function?

Because of how javascript, and most languages, scope variables, you can't access variables declared inside a function from outside a function. The variable belongs to the function's scope only, not the global scope. Fortunately, functions inherit the scope of their caller.

How do you access a variable from the outside of a function?

To access a variable outside a function in JavaScript make your variable accessible from outside the function. First, declare it outside the function, then use it inside the function. You can't access variables declared inside a function from outside a function.

How do you access a variable in a function Python?

Using the return statement to get variable from function in Python. The return statement in Python is used to return some value from a function in Python. Since we cannot access the variable defined within the function from the outside, we can return it using the return statement to get variable from function in Python ...


2 Answers

Short answer: No. Private is private is private.

Slightly longer answer: Javascript does not protect from poorly conceived or executed coding, accidentally missing the var or returning or setting a property accessor in an object (this.u = 1;) (or accessing a variable in a subscope*), or weak coffee.

When used correctly with good understanding, exposing local/private variables within a scope must be done with some kind of intention. If there is some magic voodoo that can expose your precious variable, I have not seen it. (Does the absence of evidence prove or disprove whether the yeti stalks this earth?!?)

This includes, but is not limited to:

  • Marauding aliens
  • Twerking Miley Cyrus
  • The Pope (be careful of the confessional, loose lips...)
  • Fat Albert
  • The Tea Party
  • Austin Power's cat
  • Nihilists
  • Moops
  • Baby rhinos
  • El Yeti, née, Hefe

Et cetera, et cetera.

* Gunmen on the grassy noll?

like image 180
Jared Farrish Avatar answered Oct 06 '22 12:10

Jared Farrish


No, there is no way. After the function has been executed, there is no variable left, that has a reference to the value of u. Thus, the value of u will get garbage collected and will be lost.

like image 32
basilikum Avatar answered Oct 06 '22 12:10

basilikum