fake globals
by r3wt
HTML
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
JavaScript
//factory
(function($){
var app = {},
storage = {},
scope ={
top:'',
bottom:''
};
function update()
{
var top = '(function(',
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 +='));';
scope.top = top;
scope.bottom = bot;
}
i++;
}
}
function scopify(c,args)
{
var fn = '('+c.toString()+').apply(this,args);';
var f = scope.top+fn+scope.bottom;
console.log(f);
return function() { return eval(f) }.call(this);
}
app.scopedClosure = function()
{
var args= [];
Array.prototype.push.apply(args,arguments);
var c = args.shift();
return scopify(c,args);
};
app.set = function(obj)
{
for(var prop in obj){
storage[prop] = obj[prop];
}
update();
};
app.ready = function(c){
$(function(){
scopify(c,[]);
});
};
$.app = app;
}(jQuery));
$.app.set({
test: 1,
foo: ['a','b','c']
});
$.app.ready(function(){
console.log(test,foo);
//test 1
$.app.scopedClosure(function(){
console.log(test,foo);
});
//test2
$.app.scopedClosure(function(x){
console.log(x+2);
},5);
});