Created
March 21, 2013 21:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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