所以,我想做这样的事情:
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!'});
})();
但这不起作用。
我实际上并不希望函数能够达到2个范围,我希望能够从外部设置虚函数内使用的'b'变量。
答案 0 :(得分:7)
您可以为函数或全局变量设置b
参数。
var a = 'a';
var dummy = function(b) {
...
}
或
var a = 'a';
var b;
var dummy = function() {
...
}
第一个允许您选择虚拟函数何时可以访问变量,第二个允许在任何地方访问它。
答案 1 :(得分:2)
使用此:
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) {
document.write('Variable [p1]: ', p1);
document.write('<br />');
document.write('Variable [x]: ', x);
document.write('<br />');
document.write('Variable [y]: ', y);
}
foo.applyVars(this, ['param X'], { x: "1'2\"3", y: false });
或者这个:
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) {
document.write('Variable [p1]: ', p1);
document.write('<br />');
document.write('Variable [x]: ', x);
document.write('<br />');
document.write('Variable [y]: ', y);
}
callWithVars(foo, this, ['param X'], { x: "1'2\"3", y: false });
答案 2 :(得分:2)
所以,我找到了一个更快的方法来做这样的事情:
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);