jshint screaming functions should declared outside loop, i'm confused on how this? specific part: self.onchange = function () {...}
here's loop:
for ( var j = 0; j < checkz.length; j++ ) { var self = checkz[j]; self.onchange = function () { ( var z = 0; z < psswrd.length; z++ ) { psswrd[z].type = self.checked ? 'text' : 'password'; } }; }
when move outside , assign it, function breaks 'self' becomes undefined. advice appreciated.
in case, need 1 function:
for ( var j = 0; j < checkz.length; j++ ) { var self = checkz[j]; self.onchange = changefunction; // or replace above 2 lines with: // checkz[j].onchange = changefunction; // ...if don't need `self` else. } function changefunction() { ( var z = 0; z < psswrd.length; z++ ) { psswrd[z].type = this.checked ? 'text' : 'password'; // ^^^^--- note changed `self` `this` } }
you needed self
=> this
change anyway, because originally, of functions have referred same value of self
. when create function, has enduring reference variables in context it's created, not copy of values when it's created. (more: closures not complicated) in case, can use this
because within event handler hooked way (and ways), this
element event handler hooked to.
now in general case, need refer that's changing in loop , don't happen have replacement handy it, you'd typically use builder function returns function use, this:
for ( var j = 0; j < checkz.length; j++ ) { var self = checkz[j]; self.onchange = buildchangefunction(j); } function buildchangefunction(jarg) { return function() { // use jarg in here... }; }
that way, function assign onchange
closes on argument buildchangefunction
, not j
, , argumennt doesn't change.
but again, don't need here, first solution above need.
Comments
Post a Comment