Created
September 18, 2016 12:50
-
-
Save danielgindi/53cf9eb92ab644be1468101ed9df6ff1 to your computer and use it in GitHub Desktop.
JS: Execute function given name and args - in an isolate scope
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
var execIsolated = (function () { | |
var exec = function () { | |
arguments[0](arguments[1]); | |
}; | |
return function (funcname, args) { | |
args = args || []; | |
// Determine "this" object for calling the function by name | |
var funcThis = 'this'; | |
var funcParts = func.match(/('[^'\\]*(?:\\.[^'\\]*)*')|("[^"\\]*(?:\\.[^"\\]*)*")|[[\].]|([^'"[\].]+)/g) || []; | |
var i = Math.max(funcParts.lastIndexOf('.'), funcParts.lastIndexOf('[')); | |
if (i > 0) { | |
funcThis = funcParts.slice(0, i).join(''); | |
} | |
var f = new Function(func + '.apply(' + funcThis + ',arguments)'); | |
exec(f, args); | |
}; | |
})(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment