Override global variable

I would like to modify the following code to list "hello world" from the variable "a" without passing it to a function . Is it possible?

var a = "declared variable"; var fc = function () { console.log(a); }; (function () { var a = "hello world"; fc(); }) (); 

Edit: Ah, sorry ... I haven't mentioned. I do not want to change the global variable. I just want to get the value of the variable "scope".

+4
source share
4 answers

Just uninstall var

 var a = "declared variable"; var fc = function () { console.log(a); }; (function () { a = "hello world"; fc(); }) (); 

The var parameter defines the variable in the current scope.


In response to editing, the only way to access an area should be in it (or pass it as an argument). Since you do not want to transmit it, this is the only other option that I see.

 var a = "declared variable"; (function () { var fc = function () { console.log(a); }; var a = "hello world"; fc(); }) (); 

Or, if you want to pass an area along such a construction, how it works

 var a = "declared variable"; var fc = function (scope) { console.log(scope.a); }; (function () { this.a = "hello world"; fc(this); }).apply({}); 

From a technical point of view, this is not the scale that you are passing, but it will be so.

+1
source

Let me give you an alternative answer. Never do that. This is an ugly hack that breaks sooner or sooner, it's hard to debug and slow down. Do not be lazy, miss this damn value, it will save you a lot of time in the long run.

So my answer is: you cannot achieve what you want without going through a .

0
source

You can do it as follows.

 window.a = "Hello world" 
-1
source
 var a = "declared variable"; var fc = function () { console.log(a); }; (function () { var a = "hello world"; this.a = a; // assign a to global a fc(); }) (); 
-1
source

Source: https://habr.com/ru/post/1483771/


All Articles