Created
February 10, 2012 17:41
-
-
Save gregglind/1791174 to your computer and use it in GitHub Desktop.
JavaScript bug question.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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