I have the following example app: http://dev.driz.co.uk/jsfunction/
Which runs two types of script files with the same outcome.
Script1:
var script1 = {
showMessage: function( message ) {
var el = document.getElementById('example1');
el.innerHTML = message;
}
}
and script 2:
window.script2 = function() {
function showMessage( message ) {
var el = document.getElementById('example2');
el.innerHTML = message;
}
return {
showMessage: showMessage
}
}();
They are both namespaced so I can them like:
window.onload = function() {
script1.showMessage('Hello world!');
script2.showMessage('How are you?');
};
But what's the better way forward? Script1 is the type I would normally write but it requires you to sometimes call a init function first if you have some events that need running on document load.
For example:
var script = {
init: function() {
// some events such as onlick etc..
}
};
script.init();
Script2 however is a self executing function and therefore would get around this but being a function itself would it allow the same flexibility?
Any thoughts? Suggestions or examples of how people namespace there script files to make them neater and more efficient?