Skip to content

Instantly share code, notes, and snippets.

@danielgindi
Created September 18, 2016 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielgindi/53cf9eb92ab644be1468101ed9df6ff1 to your computer and use it in GitHub Desktop.
Save danielgindi/53cf9eb92ab644be1468101ed9df6ff1 to your computer and use it in GitHub Desktop.
JS: Execute function given name and args - in an isolate scope
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