【问题标题】:Javascript ES6: How to expose variables to one function [duplicate]Javascript ES6:如何将变量公开给一个函数[重复]
【发布时间】: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 你能再次看到我的问题吗?我已编辑。我认为它没有重复。

标签: javascript ecmascript-6


【解决方案1】:

你可以的

const mergeWrapper = function(aFunction, meta) {
  return aFunction.bind(null, meta);
};

function exampleFunction(meta, temp) {
  console.log(temp);
  // can print here. without changing exampleFunction method signature.
  // in this case should be 'stackoverflow'
  console.log(meta);  
}

let func = mergeWrapper(exampleFunction, 'stackoverflow');
func('temp');
func('temp2');

你已经绑定了 meta 作为第一个参数,所有的调用都会得到 meta 的值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 2018-07-10
    • 2013-05-01
    • 2019-06-29
    • 2013-01-03
    • 2020-11-16
    相关资源
    最近更新 更多