Skip to content

Instantly share code, notes, and snippets.

@skerit
Created March 21, 2013 21:09
Show Gist options
  • Save skerit/5216766 to your computer and use it in GitHub Desktop.
Save skerit/5216766 to your computer and use it in GitHub Desktop.
"Inject" something into a function's scope (NOT context) This is just a proof-of-concept. Because it uses eval() on every execution you get a 99% performance hit.
Function.prototype.compel = function(scope, args, scope_args) {
var code = '';
// Every scope_args entry will be added to this code
for (var name in scope_args) {
code += 'var ' + name + ' = scope_args["' + name + '"];';
}
// eval the code, so these variables are available in this scope
eval(code);
if (!this.__source__) this.__source__ = String(this);
eval('var fnc = ' + this.__source__);
// Apply the function source
fnc.apply(scope, args);
}
// This should also be accessible
var a = 'a';
// The dummy function we'll "compel" later
var dummy = function() {
// Print out var 'a', from the scope above
console.log('Dummy a: ' + a);
// Print out 'b', from the 'compelled' scope
console.log('Dummy b: ' + b);
}
(function() {
dummy.compel(this, [], {b: 'test-one'});
dummy.compel(this, [], {b: 'test-two'});
dummy.compel(this, [], {b: 'test-three'});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment