How can I execute a JS function from the top of the stack?

I would like to execute a function from the top of the stack. That is, any variables defined with "var" must be defined in a global sense. Is it possible? fn.call (window) does not work.

<script>
  var foo = "I am top level foo.";

  var fn = function(){
    var foo = "Setting foo from in a function";
  }

  fn.call(window);  //doesn't work, var is still set locally in fn.
  alert(foo);  //desired effect will alert "setting foo from in a function"
</script>

Note: I fully understand that not specifying "var" makes an element of a global variable. The problem is that I can not specify the contents of "fn", it is user-defined, but it is expected that it will be launched from the top level.

I wish to use eval if necessary.

+3
source share
4 answers

, , foo . var foo , ( ).

var foo , . , +. , :

var fn = function() {
   this.foo = "Setting foo from in a function";
};

, :

var fn = function() {
  window.foo = "Setting foo from in a function";
};

, ?

+ foo , , . , , . , , foo. , , ; .

UPDATE

, - , . , , , :

var foo = 2;

var fn = function() {
   var foo = 3;
}

console.log(foo); //prints 2

var fnSource = fn.toSource();
eval(fnSource.replace(/^\(function\s*\(\)\s*{/, "").replace(/}\s*\)$/, ""));

console.log(foo); //prints 3

(function () { }) , , eval.

, , .

+2

. : local. . , , .

- .

, , , toSource() var. toSource(), function {... }, eval() . . , .


, . var, . var , , , .

var fn = function() {
    foo = "Setting foo from in a function";
}

, window, :

var fn = function() {
    window.foo = "Setting foo from in a function";
}
+1

var this. , window, "" :

window.foo = "I am top level foo.";

var fn = function(){
    this.foo = "Setting foo from in a function";
}

fn.call(window);
alert(foo);

Then you can also call the function with a different context:

var anObject = { foo: "Initial Value" };
fn.call(anObject);
alert(anObject.foo); // Will be the modified value
+1
source

You can get this effect without changing fn, but this code is not for the faint of heart:

<script type="text/javascript">
var gFoo = "";

var fn = function() {
    var foo = "Setting foo from in a function";
}

var fnText = fn.toString();
var newFunction = fnText.substring(0, fnText.length - 1) + "gFoo = foo; }";

eval("var x = " + newFunction + "; x();");
alert(gFoo);
</script>
0
source

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


All Articles