Skip to content

Instantly share code, notes, and snippets.

@MaxMotovilov
Last active December 14, 2015 03:59
Show Gist options
  • Save MaxMotovilov/5024977 to your computer and use it in GitHub Desktop.
Save MaxMotovilov/5024977 to your computer and use it in GitHub Desktop.
eval() in closure with subsequent read-write access to closure
function bindClosureSlot( name ) {
return "function(v){ if( arguments.length<1 ) return " + name + "; else return " + name + "=v; }";
}
function evalInClosureExt( code, closure ) {
return Function.apply(
null,
Object.keys( closure ).concat(
"return [" +
code + "," +
"{" +
Object.keys( closure ).map(
function( k ) {
return k + ":" + bindClosureSlot( k );
}
).join(",") +
"}" +
"];"
)
).apply(
null,
Object.keys( closure ).map( function(k){ return closure[k]; } )
)
}
console.log( "Test 1" );
var ext_fn = evalInClosureExt(
"function(){ return x++; }",
{ x: 5 }
),
fn = ext_fn[0],
closure = ext_fn[1];
console.log( "x = ", closure.x() );
console.log( "fn() = ", fn() );
console.log( "x = ", closure.x() );
console.log( "x = ", closure.x( 10 ) );
console.log( "fn() = ", fn() );
console.log( "x = ", closure.x() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment