As Triptych points out, you can call any global scope function by finding it in the contents of the host object.
A cleaner method that significantly pollutes the global namespace is to explicitly put functions into an array directly like this:
var dyn_functions = []; dyn_functions['populate_Colours'] = function (arg1, arg2) { // function body }; dyn_functions['populate_Shapes'] = function (arg1, arg2) { // function body }; // calling one of the functions var result = dyn_functions['populate_Shapes'](1, 2); // this works as well due to the similarity between arrays and objects var result2 = dyn_functions.populate_Shapes(1, 2);
This array can also be a property of some object other than the global host object, which also means that you can effectively create your own namespace like many JS libraries such as jQuery do. This is useful for reducing conflicts if, when you enable several separate utility libraries on one page and (in other parts of your resolution), you can simplify the reuse of code on other pages.
You can also use an object that you can find cleaner:
var dyn_functions = {}; dyn_functions.populate_Colours = function (arg1, arg2) { // function body }; dyn_functions['populate_Shapes'] = function (arg1, arg2) { // function body }; // calling one of the functions var result = dyn_functions.populate_Shapes(1, 2); // this works as well due to the similarity between arrays and objects var result2 = dyn_functions['populate_Shapes'](1, 2);
Please note that using an array or an object, you can use any method of installation or access to functions and, of course, store other objects there. You can also reduce the syntax of any of the methods for contant that is not syntactic using JS letter notation as follows:
var dyn_functions = { populate_Colours:function (arg1, arg2) {
Editing: of course, for larger blocks of functionality, you can expand it above to the very common βmodule templateβ, which is a popular way to encapsulate code functions in an organized way.
David Spillett Jun 09 '09 at 12:51 2009-06-09 12:51
source share