I see this works in below code only in init function and functions called within init (e.g.: onSearchClick). Can anyone explain why this is not working in onSearchClick? And what this pattern is called as?
(function() { var e, Search = { ele: { sb : $('.searchSubmit'), st : $('.searchText') }, vars: { debug: true }, init : function() { e = this.ele; this.addEvents(); }, addEvents : function() { this.ele.sb.bind('click', this.onSearchClick); //Search.ele.sb.bind('click', this.onSearchClick); //Both, this. and Search. work }, onSearchClick : function() { Search.log('onSearchClick: - '); //this.log('onSearchClick: - '); //Only Search. works, this. not }, log : function(p_sMessage) { if(!Search.vars.debug) { return; } else { if(window.console) { console.log(p_sMessage); }} } }; window.Search = Search; window.e = e; }()); Search.init();
elevariable further.thiscontext withthis.ele.sb.bind('click', this.onSearchClick.bind(this));thisis special in JS, and has various uses. From developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… :"When a function is used as an event handler, itsthisis set to the element the event fired from ...". This behaviour is overriding how you are trying to usethisand therefore creates an issue.