So, I want to do something like this:
var a = 'a';
var dummy = function() {
// Print out var 'a', from the scope above
console.log('Dummy a: ' + a);
// Print out 'b', from the 'compelled' scope
console.log('Dummy b: ' + b);
}
(function() {
var b = 'otherscope';
// I know apply won't work, I also don't want to merge scopes
dummy.apply(this);
// I want something like this:
dummy.compel(this, [], {b: 'injected!'});
})();
But that won't work.
I don't actually want a function to be able to reach 2 scopes, I DO want to be able to set the 'b' variable used inside the dummy function from the outside.
You can make b a parameter for the function, or a global variable.
var a = 'a';
var dummy = function(b) {
...
}
or
var a = 'a';
var b;
var dummy = function() {
...
}
The first allows you to choose when the dummy function has access to the variable, the second allows it to be accessed everywhere.
Use this:
Function.prototype.applyVars = function(Ç$Êscope, Ç$Êparams, Ç$Êscope_variables) {
if (Ç$Êscope_variables) {
var Ç$Êvariable, Ç$ÊdefVars = [];
for (Ç$Êvariable in Ç$Êscope_variables) {
if (Ç$Êscope_variables.hasOwnProperty(Ç$Êvariable)) {
Ç$ÊdefVars.push(Ç$Êvariable + '=Ç$Êscope_variables["' + Ç$Êvariable + '"]');
}
}
eval('var ' + Ç$ÊdefVars.join(',') + ';');
return eval('(' + this + ').apply(Ç$Êscope, Ç$Êparams);');
}
return this.apply(Ç$Êscope, Ç$Êparams);
}
// Example
function foo(p1) {
console.log('Variable [p1]', p1);
console.log('Variable [x]', x);
console.log('Variable [y]', y);
}
foo.applyVars(this, ['param X'], { x: "1'2\"3", y: false });
Or this:
function callWithVars(Ç$Êfn, Ç$Êscope, Ç$Êparams, Ç$Êscope_variables) {
if (Ç$Êscope_variables) {
var Ç$Êvariable, Ç$ÊdefVars = [];
for (Ç$Êvariable in Ç$Êscope_variables) {
if (Ç$Êscope_variables.hasOwnProperty(Ç$Êvariable)) {
Ç$ÊdefVars.push(Ç$Êvariable + '=Ç$Êscope_variables["' + Ç$Êvariable + '"]');
}
}
eval('var ' + Ç$ÊdefVars.join(',') + ';');
return eval('(' + Ç$Êfn + ').apply(Ç$Êscope, Ç$Êparams);');
}
return Ç$Êfn.apply(Ç$Êscope, Ç$Êparams);
}
// Example
function foo(p1) {
console.log('Variable [p1]', p1);
console.log('Variable [x]', x);
console.log('Variable [y]', y);
}
callWithVars(foo, this, ['param X'], { x: "1'2\"3", y: false });
So, I found a little faster way to do such a thing:
var C = function(ctx, funcBody){
var newBody = [];
for(var k in ctx){
var i = "var "+k + " = ctx['"+k+"'];";
newBody.push(i);
}
var res = "return function(t){ " +funcBody+ " }";
newBody.push(res);
var F = new Function("ctx", newBody.join('\n'));
return F(ctx);
}
var newFunction = C({"foo":10, "bar":100}, "return foo+bar*t")
newFunction(50);