2017-09-23 37 views
0

例如。我有這樣的代碼:Javascript ES6:如何將變量暴露給一個函數

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做的「東西」。因此,在功能內部,我可以撥打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

@melpomene因爲我再次縮短了我的問題。我想在「環境」中包裝我的功能。我可以編寫一個包裝函數並使用currying。但是如果我這樣做,我會爲所有需要的函數手動編寫包裝函數。所以我想實現一個像上面那樣的包裝器。 –

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

如果你已經綁定元作爲第一個參數,和所有通話將獲得的元