fake globals

by r3wt

HTML

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

JavaScript

//factory
(function($){
  
  var app = {};
  var storage = {};
  
  app.set = function(obj){
    for(var prop in obj){
      storage[prop] = obj[prop];
    }
  };
  
  function scopify(c,args)
  {
    var top = '(function(',
        fn = '('+c.toString()+').apply(this,args);',
        bot = '}(',
        i=0,
        len = Object.keys(storage).length;
    for(var prop in storage){
      top +=prop;
      bot += 'storage.'+prop;
      if(i!==len-1){
        top +=',';
        bot +=',';
      }else{
        top +='){';
        bot +='));';
        var f = top+fn+bot;
        console.log(f);
        return function() { return eval(f) }.call(this);
      }
      i++;
    }
  }
  
  app.scopedClosure = function(){
    var args= [];
    Array.prototype.push.apply(args,arguments);
    var c = args.shift();
    return scopify(c,args);
  };
  
  $.app = app;
}(jQuery));

$.app.set({
  test: 1,
  foo: ['a','b','c']
});


//test 1
$.app.scopedClosure(function(){
  	console.log(test,foo);
});

//test2 
$.app.scopedClosure(function(x){
  console.log(x+2);
},5);