I have a function, with this inside it:
var fobj = function(){};
var my_obj = fobj.extend({
test: function(){
this.year = 1999;
my_fmagic.doMagic([
{
field: 'year',
type: 'function',
value: function(data_from_doMagic){
console.log(data_from_doMagic, this.year);
return data_from_doMagic == this.year;
}
}
]);
}
});
Then, the doMagic function:
var fmagic = function(){};
var my_fmagic = fmagic.extend({
doMagic: function( rules ) {
var data_from_doMagic = 1999;
_.each(rules, function(rule) {
switch(rule.type) {
case "function":
var f = _.wrap(rule.value, function(func){
return func( data_from_doMagic );
});
f();
break;
}
});
}
});
The idea is: pass an array of "rules" to doMagic and let it do the rest.
Expected result: test() should return true (well, in this example it won't return anything, obviously, because there's no return, but the value field of the rule should be true.)
Problem: Instead the result being true it's false, because the function f() in doMagic doesn't know what the variable year is, and so it compares "1999" with "undefined".
As you can see I know where the problem is, but I can't think about any solution.
Ideas?
Regards
return data_from_doMagic == year;. Does the script ever reach that point? And if it does, what's the value ofyear?f: jsbin.com/exaqad There's no scope issue. The function you're passing asvalueclearly has access toyearbecause it closes over the context in whichyearis defined, and similarly the wrapper function has access todata_from_doMagicfor the same reason.f()you've now added to the question, and throws anUnexpected identifiererror (probably because you didn't include backbone). The idea is to demonstrate the problem.