【发布时间】:2017-09-23 20:57:39
【问题描述】:
例如。我有这个代码:
export const mergeWrapper = function(aFunction, meta) {
return aFunction;
};
function exampleFunction(temp) {
console.log(temp);
// can print here. without changing exampleFunction method signature.
// in this case should be 'stackoverflow'
console.log(meta);
}
mergeWrapper(exampleFunction, 'stackoverflow')('hello');
我想在mergeWrapper 中做“某事”。这样,在 aFunction 中,我可以调用 meta。我尝试过诸如:
export const mergeWrapper = function(aFunction, meta) {
aFunction.bind(this);
return aFunction;
};
但它不起作用。我该怎么做。
我的想法是因为我可以使用柯里化来编写某种函数。例如:
export const wrapperFunction = function(meta) {
return function(temp) {
console.log(temp);
console.log(meta);
}
}
wrapperFunction('StackOverFlow')('hello');
但是这样写会让我为所有函数编写包装器。所以我想写一个helper。
谢谢
【问题讨论】:
-
这看起来像是一个 XY 问题。你打算用这个做什么?
-
@melpomene 因为我又缩短了我的问题。我想将我的功能包装在“环境”中。我可以编写一个包装函数并使用柯里化。但如果我这样做,我将为所有需要的函数手动编写包装函数。所以我想实现一个像上面这样的包装器。
-
一般来说,你不能这样做,因为 JavaScript 不支持动态作用域。但是,正如下面的答案所示,您始终可以将
meta作为参数传递给函数。另一种方法是在你的函数中使用this.meta。 -
@melpomene 编辑了我的问题。请看一看。
-
@AaditMShah 你能再次看到我的问题吗?我已编辑。我认为它没有重复。