5

所以,我想做这样的事情:

    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”变量。

4

3 回答 3

6

您可以b为函数或全局变量创建参数。

var a = 'a';
var dummy = function(b) {
   ...
}

或者

var a = 'a';
var b;
var dummy = function() {
   ...
}

第一个允许您选择虚拟函数何时可以访问变量,第二个允许您在任何地方访问它。

于 2013-03-21T19:17:27.273 回答
3

所以,我找到了一种更快的方法来做这样的事情:

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);
于 2015-04-24T11:55:04.780 回答
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 });

于 2014-02-12T14:43:20.727 回答