I am implementing a require/load function which retrieves and executes a remote piece of javascript code. It works fine, and I am using a workaround to give it arguments by basically declaring global variables, but I wanted to know what was the best way to pass arguments in this situation. Here is the function that loads the remote script
Module.require = function (moduleName , args){
if (! Module.has(moduleName)){
dojo.xhrGet({
url: 'module.require.php',
handleAs: "javascript",
content : {
module : moduleName
},
load: function() {
},
error: function(errorMessage) {
console.log('there was an error with Module.require()');
console.error(errorMessage);
}
});
}
};
My first question is what context is moduleName executed in when the code stored in moduleName.js is fetched and dynamically executed? If it is in the scope of the function Module.require then I can easily refer to args. If it is executed in the global scope (window) then I know how to declare local variables (anonymous function call (function(){}());) but how do I pass arguments? I hope there is an easy way to do this as I do not wish to pass all the arguments over to the server. Not only is it difficult to parse them via PHP, there code potentially be many arguments.
EDIT: James Khoury mentioned how I can use f.apply() and f.call() to pass arguments, so what I need to know now is what context the script is loaded in on execution. If it's in the scope of the function, I suppose I can call it like so f.call(this , args);. And if I can do this, is there anyway to call an anonymous function? I ask because I am creating modules which wrap the user code to ensure that all variables the user declares remain local, therefore, it would be best to ensure the wrapper function is also not global.
Thanks