1
What’s the difference of writing Javascript code in the following ways:
Original form:
'use strict';
var openCtrl = document.getElementById('btn-search'),
closeCtrl = document.getElementById('btn-search-close'),
searchContainer = document.querySelector('.search'),
inputSearch = searchContainer.querySelector('.search__input');
function init() {
initEvents();
}
function initEvents() {
openCtrl.addEventListener('click', openSearch);
closeCtrl.addEventListener('click', closeSearch);
document.addEventListener('keyup', function(ev) {
// escape key.
if( ev.keyCode == 27 ) {
closeSearch();
}
});
}
function openSearch() {
searchContainer.classList.add('search--open');
inputSearch.focus();
}
function closeSearch() {
searchContainer.classList.remove('search--open');
inputSearch.blur();
inputSearch.value = '';
}
init();
Now what difference does it make this way:
;(function(window) {
'use strict';
var openCtrl = document.getElementById('btn-search'),
closeCtrl = document.getElementById('btn-search-close'),
searchContainer = document.querySelector('.search'),
inputSearch = searchContainer.querySelector('.search__input');
function init() {
initEvents();
}
function initEvents() {
openCtrl.addEventListener('click', openSearch);
closeCtrl.addEventListener('click', closeSearch);
document.addEventListener('keyup', function(ev) {
// escape key.
if( ev.keyCode == 27 ) {
closeSearch();
}
});
}
function openSearch() {
searchContainer.classList.add('search--open');
inputSearch.focus();
}
function closeSearch() {
searchContainer.classList.remove('search--open');
inputSearch.blur();
inputSearch.value = '';
}
init();
})(window);
– Guilherme Nascimento
Also related: http://answall.com/questions/17343/an%C3%A1lise-e-projeto-em-javascript/17355#17355
– bfavaretto
I closed it, but I don’t know if it was a good idea. It has several related contents, but none are exact duplicates. The closest I could find was this third link I put in the duplicate warning
– bfavaretto
@bfavaretto in my view this http://answall.com/q/23785/3635 responds perfectly.
– Guilherme Nascimento