Consider this code:
function Elements() {
this.mainSection = document.querySelector('.main-section');
this.searchBtn = document.getElementById('search');
this.searchBar = document.querySelector('.search-bar');
...
}
var initiate = new Elements();
initiate.toggleBar = function() {
console.log(this.mainSection);
}
initiate.addClick = function() {
this.searchBtn.addEventListener('click', this.toggleBar );
}
initiate.addClick();
On click event it returns undefined
, with parenthesis it runs function automatically.
Why eventlistener behave this way?
P.S. I'm just learning Javascript, and trying to write flexible code. Is this a good practice what I am doing, or am I over complicating things?