Entering a variable in the callback function area

Can I add a variable to the callback area? I want to achieve:

  ...
 Foo.prototype.bar = function (fn) {
     var baz = "baz!";
     fn.call (this);
 }
 ...
  Foo.bar (function () {
     console.log (baz) // gives "baz!"
 });

I know that I can pass the baz variable as an argument or this , but I'm interested in something like the above.

+4
source share
2 answers

No, It is Immpossible. The only ways are the ones you specified: as an argument or in this .

+4
source

How to do it:

 var Foo = function(){} Foo.prototype.handle = function(fn) { var baz = "baz !"; eval('(' + fn.toString() + ')();'); } var foo = new Foo; foo.handle(function (){ console.log(baz); }); 
0
source

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


All Articles