Skip to content

Instantly share code, notes, and snippets.

@gregglind
Created February 10, 2012 17:41
Show Gist options
  • Save gregglind/1791174 to your computer and use it in GitHub Desktop.
Save gregglind/1791174 to your computer and use it in GitHub Desktop.
JavaScript bug question.
/*
bindFunctions as implemented below has a bug.
1. What is the bug?
2. How do you fix it?
All functions have the args:
functionList: list of functions
context: an object that should be used as the 'this' of those functions
*/
function bindFunctions0(functionlist,context) {
var i,cmd;
for (i = 0; i < functionlist.length; i++) {
cmd = functionlist[i];
context[cmd.name] = function(){ return cmd.apply(context, arguments); };
}
return context;
}
function test(bindingfn) {
var somecmnds = [function oner(v){return [this.a, v, 1]}, function twoer(y){return [this.a, y, 2]}];
var mycontext = bindingfn(somecmnds,{'a':'AA'});
console.log(mycontext.oner('Q'));
console.log(mycontext.twoer('Q'));
};
test(bindFunctions0);
/* Solutions
Recall the block scoping rules for JS!
*/
/* solution 1, add another closure */
function bindFunctions1(functionlist,context) {
var i,cmd;
for (i = 0; i < functionlist.length; i++) {
cmd = functionlist[i];
context[cmd.name] = (function(cmd){return function(){return cmd.apply(context,arguments)} })(cmd);
}
return context;
}
test(bindFunctions1);
/* solution 2, 'let' keyword, available in recent js (such as FF web console */
function bindFunctions2(functionlist,context) {
var i,cmd;
for (i = 0; i < functionlist.length; i++) {
let cmd = functionlist[i];
context[cmd.name] = function(){ return cmd.apply(context, arguments); };
}
return context;
}
test(bindFunctions2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment