javascript closures onreadystatechange -


why code not parsed when change

var comments_switcher = (function(){     var switcher = null;     var show = 'show comments';     var hide = 'hide comments';     function init(){         if ( switcher == null ) switcher = document.getelementbyid("comments_switch");     }        function switched_on(){              return switcher.value == show;     }     return {         trigger : function(do_init){             if ( do_init ) init();             switcher.value = switched_on() ? hide : show;         }     } })(); 

into

var comments_switcher = (function(){     var switcher = null;     var show = 'show comments';     var hide = 'hide comments';     function init(){         if ( switcher == null ) switcher = document.getelementbyid("comments_switch");     }         return {             trigger : function(do_init){                if ( do_init ) init();                switcher.value = switched_on() ? hide : show;             },             switched_on : function(){                       return switcher.value == show;             }     } })(); 

and why xmlhttp.onreadystatechange not work when giving function object instead of function() {}?

you need reference switched_on method returned object since it's no longer variable.

you can use this.switched_on(), assuming trigger() method invoked comments_switcher.trigger().

return {     trigger : function(do_init){         if ( do_init ) init();         switcher.value = this.switched_on() ? hide : show; // -----------------------^     },     switched_on : function(){               return switcher.value == show;     } } 

but again, relies on this being set returned object. depend on how you've invoked trigger.


if did:

xmlhttp.onreadystatechange = comments_switcher.trigger; 

...it fail. change to:

xmlhttp.onreadystatechange = function() { comments_switcher.trigger() }; 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -