Task 3: Questions
The major reason to organise your code into modules: to declare private details that are not important to the outside world and to avoid conflicts and accidentally overriding existing variables.
He refers to code that doesn't use modules, and creates many global variables as spaghetti code.
These are simple examples, in real-life you usually expose more than just
init
. Difference between modules and classes?
- What people call "classes" in JavaScript doesn't offer any notion of privacy. Everything is public. In modules everything is private. There are a lot of other differences, it's the most important.
JavaScript doesn't have classes. He doesn't like classes. He prefers OLOO (objects linked to other objects) to OO (object oriented).
In what scenario does it makes sense to pass a variable to an IFEE (or module)?
- consider this organisation:
(function(){
// 98 private variables
// spaghetti goes here
// these things get public
window.foo = foo;
window.bar = bar;
})();
We could pass in window
to the above code:
(function(global){
// 98 private variables
// spaghetti goes here
// these things get public
global.foo = foo;
global.bar = bar;
})(window);
It's makes it more clear what is global. Also, in the case when you're using several frameworks on your page (jQuery, DOJO) and they all want to use
$
, so you no longer know to which one it belongs to.Then you can pass in the framework to your IFEE.
(function(global, $){
// 98 private variables
// spaghetti goes here
// these things get public
global.foo = foo;
global.bar = bar;
})(window, jQuery);
These are the two main raisons to pass variables into an IFEE.To what extend is document.ready
necessary?- Many people claim, that you can put your script tags in the bottom of html code and you don't even need
document.ready
. This claim is false. Many times it turns out to be true by accident, but not always. The DOM is not always ready at this point. He suggests not to assume anything about the DOM being ready. On the other hand there's a lot of stuff going in the code, that doesn't even need the DOM to be ready, still people wrap those two. For example an AJAX call. It doesn't need the DOM.
document.ready
is for code that needs to deal with the DOM. document.ready
is the same as DOMContentLoaded
:
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
My note: except that if you add several DOMContentLoaded
then they will override each other. You need to add a utility to be able to run more than one handler for the DOMContentLoaded
event.