Javascript: Dynamically add functions to object -
i have generalwrapper object calls statically-defined functions in library1 , library2 objects.
the aim calling generalwrapper.somefunc(), call library1.somefunc() , library2.somefunc() without me having explicitly create function in generalwrapper called somefunc.
i attempt implement in __preamble method below:
var generalwrapper = { __modespopulated: false, __validmodes: { // 3 of these spoonfunc: 1, // functions exist knifefunc: 1, // in library1 , forkfunc: 1 // library2 }, __switchmode: function(funcname){ if (funcname in generalwrapper.__validmodes){ console.log("calling function", funcname) generalwrapper.__preamble() library1[ funcname ](); // call mode in library1 library2[ funcname ](); // call mode in library2 } }, /* attach valid modes general wrapper @ runtime */ __preamble: function(){ if (!generalwrapper.__modespopulated) { (var mode in generalwrapper.__validmodes) { generalwrapper[mode] = function(){ generalwrapper.__switchmode(mode) }; } generalwrapper.__modespopulated = true } generalwrapper.__otherprestuff(); }, __otherprestuff: function(){ // stuff }, functhatalwaysgetscalled: function(){ generalwrapper.__switchmode("forkfunc"); } } var library1 = { forkfunc(){console.log("lib1","fork")}, spoonfunc(){console.log("lib1","spoon")}, knifefunc(){console.log("lib1","knife")} } var library2 = { forkfunc(){console.log("lib2","fork")}, spoonfunc(){console.log("lib2","spoon")}, knifefunc(){console.log("lib2","knife")} } // okay, let's initialise object generalwrapper.functhatalwaysgetscalled(); for reason calls generalwrapper.spoonfunc() , generalwrapper.knifefunc() defer fork output.
i imagine problem stems anonymous function assignment on generalwrapper[mode] = blah line js treats same function each time, don't know how around this.
please advise.
solution:
change line:
for (var mode in generalwrapper.__validmodes) into this:
for (let mode in generalwrapper.__validmodes) explanation:
what happens in code (when binding functions in __preamble's loop) create anonymous function, totally fine. problem is, anon function has received mode reference local variable, it's value not automatically cloned rather accessed @ runtime. main problem you've used var keyword, means "hoisted variable" (it gets declared @ top of function defined inside, if it's somewhere in middle of function's code). in scenario, need "block-scoped" variable, bound each loop iteration separately.
you can read more variables hostings on mdn:
var @ mdn
let @ mdn
one thing have know - let introduced in es2015, if worry backward compatibility older browsers, either have use function.prototype.bind or iife
Comments
Post a Comment