2017-09-23 6 views
0

たとえば、次のようになります。Javascript ES6:1つの関数に変数を公開する方法

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'); 

ただし、このように記述すると、すべての機能のラッパーが作成されます。だから私はヘルパーを書いてみたいです。

おかげ

+0

の値になるだろうXY問題。あなたはこれを何のために使うつもりですか? – melpomene

+0

@メルポメン私は再び私の問題を短縮しているため。私は "環境"の中に私の機能を包み込みたい。私はラッパー関数を記述し、カリングを使用することができます。しかし、私がそれを行うならば、私はすべての必要な機能のために手動でラッパー機能を書いていきます。だから私は上記のようなラッパーを実装したい。 –

+0

一般的に、JavaScriptは動的スコープをサポートしていないため、これを行うことはできません。しかし、以下の答えが示唆するように、関数に引数として 'meta'を渡すことができます。もう一つの方法はあなたの関数の中で 'this.meta'を使うことです。 –

答えて

0

あなたが最初の引数としてのメタをバインドされている

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');

を行うことができ、およびすべてのコールは、これがどのように見えるのメタ

関連する問題