我有一个functionA,它接受一个函数作为参数。我想在functionA中操纵该函数的参数,并将其作为functionC返回。我发现可以使用.apply()完成此操作,但是functionB的原始上下文丢失了,而是由functionA代替。

例如,

var factory = {
   return {
       fnB: function() {}
   }
};

fnA(fn) {
    return fnC(params) {
        var customparams = [params, {something: else}]
        return method.apply(null, customparams);
     }
}

var load = fnA(factory.fnB);
load(params);


但是,当我执行load(params)时,我失去了functionB的上下文。 FunctionB被定义为工厂的方法。我该怎么办?谢谢!

最佳答案

我将假定method实际上是fn,并且functionB是分配给对象属性的函数,并且各种语法错误在您的实际代码中不存在:

var obj = {
    name: "foo",
    functionB: function() {
        console.log(this.name); // <== Using `this` to refer to `obj`
    }
};

function functionA(fn) {
    return function functionC(params) {
        var customparams = [params, {something: "else"}];
        return fn.apply(null, customparams);
    };
}

var load = functionA(obj.functionB);
load("a", "b"); // Fails because `this` in the call to `functionB` isn't `obj`


如果是这样,您可以在两个很麻烦的情况下修复它:

1)通过使用Function#bind并将functionB传递到functionA

var load = functionA(obj.functionB.bind(obj));
load("a", "b"); // Works




var obj = {
  name: "foo",
  functionB: function() {
    snippet.log(this.name); // <== Using `this` to refer to `obj`
  }
};

function functionA(fn) {
  return function functionC(params) {
    var customparams = [params, {
      something: "else"
    }];
    return fn.apply(null, customparams);
  };
}

var load = functionA(obj.functionB.bind(obj));
load("a", "b"); // Works

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>





2)通过在调用functionA时使用的fn as Bergi suggested中添加第二个参数(参见代码段)-许多ES5 Array方法都使用这种方法,例如:



var obj = {
  name: "foo",
  functionB: function() {
    snippet.log(this.name);
  }
};

function functionA(fn, thisArg) {           // <=== Accepting thisArg
  return function functionC(params) {
    var customparams = [params, {
      something: "else"
    }];
    return fn.apply(thisArg, customparams); // <=== Using it
  };
}

var load = functionA(obj.functionB, obj);   // <=== Passing it
load("a", "b"); // Works

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

08-03 14:52