Last active
February 13, 2020 18:47
-
-
Save matthewstokeley/36b088f008e9c3ab4c36 to your computer and use it in GitHub Desktop.
execute a function by string name in a namespace without eval
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
// 'pojo' idiom for namespacing javascript | |
var namespace = {}; | |
var x = 'fn'; | |
namespace.fn = function() { | |
console.log('fin'); | |
} | |
// execute function by string name | |
var execute = function(context, name, args) { | |
return context[name].apply(context, args); | |
}; | |
//execute(namespace, x); | |
// attached to the string prototype | |
String.prototype.execute = function(context, args) { | |
if (!context[this]){ | |
return false; | |
} | |
context[this].apply(context, args); | |
}; | |
x.execute(namespace); |
Breaking all rules
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JavaScript idiom for namespacing before es6 / commonjs modules