我有一个函数,它接受一个函数作为参数。我想在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被定义为工厂的方法。我怎么能这样做?谢谢!
答案 0 :(得分:2)
我假设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
as Bergi suggested添加第二个参数,它在调用fn
时使用(参见代码段) - 许多ES5使用此方法{ {1}}方法,例如:
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