Defining javascript prototype functions through a loop -
this question has answer here:
i try define prototype functions array. in following example : black rabbit should 'toto' doesn't ! why ?
function rabbit ( type ) { this.type = type ; } var funcs = ["says", "doesnt_say"]; for(var i=0;i<funcs.length;i++) { var f = funcs[i]; rabbit.prototype[f] = function ( line ) { alert(" " + this.type + " rabbit " + f + " '" + line + " '") ; }; } var blackrabbit = new rabbit ("black") ; blackrabbit.says("toto"); visible on http://jsfiddle.net/xou11bgu/
the problem variable "f" shared functions create, , end having value of last function name.
you can use function construct functions:
rabbit.prototype[f] = function(f) { return function ( line ) { alert(" " + this.type + " rabbit " + f + " '" + line + " '") ; }; }(f); this instance of extremely common javascript stumbling block; there many, many other similar questions here on stackoverflow, they're hard find because until know problem it's hard know you're looking for.
Comments
Post a Comment