V
V
Victor2011-05-05 12:39:21
JavaScript
Victor, 2011-05-05 12:39:21

Is it possible to pass context (Scope) between closures (Closure)?

// рабочий результат
var invoke = function(fn){
  var str = 'var test = \'sss\';';
  alert(fn)
  var fnxt = new Function(str+fn);
  fnxt();
}
var tester = 'alert(test);'

invoke(tester);

// желательный результат
var invoke_real = function(fn){
  var test = 'sss';
  alert(fn)
  // дальше, само собой -- не работает, т.к. test отсутствует для scope tester_real'a
  fn();
}
var tester_real = function(){ alert(test); }

invoke_real(tester_real);

* This source code was highlighted with Source Code Highlighter.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
mark_ablov, 2011-05-05
@mark_ablov

I don’t know how it suits you, but only through working with the object it came to mind:


    var invoke_real = 
    {
        real: function(fn)
        {
           this.test = 'sss';
           fn(this);
           this.f();
        }
    };
    var tester_real = function(ctx){ctx.f = function() {alert(this.test);};};

    invoke_real.real(tester_real);

scope is only inherited if the function is defined inside another function, so I doubt it could be much simpler.

V
Victor, 2011-05-05
@wentout

That is, for now, the “lack of thoughts” has led here:

var invoker = {
   init  : function(fn){
    invoker.arr[fn] = window[fn];
    window[fn] = function(){
      var test = 'sss';
      alert('+1 '+test)
      invoker.arr[fn]();
    };
  }
  , del  : function(fn){
    window[fn] = invoker.arr[fn];
    delete invoker.arr[fn];
  }
  , arr  : []
}
var tester = function(){ alert(222); try{ alert(test); }catch(e){ alert(e); /* ref err */ } }
invoker.init('tester');
alert(111);
tester();
alert(333);
invoker.del('tester');
tester();
* This source code was highlighted with Source Code Highlighter.

A
Alexander Keith, 2011-05-06
@tenbits

Maybe this option will work?

function test(args) {
  console.log(this.title1, test.title1, args.title2); // -> Hello! Hello! Hello World
}
(function(){
  test.__proto__.title1 = 'Hello!';
  test = test.bind(test, {title2: 'Hello World'});
    
})();
test();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question