i have function in testfun.js
var testfunc=function{ var hascar=false; return{ checkcar: function(){ for(var i=0; i<5; i++){ mycar.check(hascar); //defined in following mycar.js } } } }(); another function in mycar.js
var mycar=function(){ var createcar=function(){ //create car //var car = new car(); } return{ check: function(hascar){ console.log(hascar); //problem here: fierbug console output "false" check_button has been clicked, why? var handler=function(){ if(!hascar) createcar(); hascar=true; } //check_button button on ui check_button.click(handler); } } }(); as see in mycar module pattern, when check_button clicked, call createcar() function, , change hascar value false true.
the hascar defined in testfunc module pattern, , pass mycar.check(hascar).
i have firebug console output inside mycar.check() function, expect when mouse clicked check_button, console output true, false, why?? use hascar check check_button has been clicked once or not, if hold false value, can not know it. how rid of this?
primitive values passed by value , not reference.
thus assigning true hascar inside click event handler (in mycar.check) not change value of hascar defined in testfunc.
you use object instead:
var testfunc= (function(){ var hascar = {val: false}; // ... }()); var mycar=(function(){ //... return{ check: function(hascar){ console.log(hascar.val); var handler=function(){ if(!hascar.val) createcar(); hascar.val=true; } check_button.click(handler); } } }()); or define hascar variable in scope accessible both functions.
update:
you still false in console because hascar.val set true after clicked button , never call console.log when click button.
using loop here not tell anything. more appropriate testing be, given setup:
var hascar = {val: false}; mycar.check(hascar); // output false // click button mycar.check(hascar); // output true have @ demo.
further notes:
- for better compatibility, surround self invoking functions parenthesis.
- you adding new click handler every time
mycar.ceckcalled. don't think desired. - the structure of application quite confusing (at least me ;)).
Comments
Post a Comment