![](/img/trans.png)
[英]How to pass parameters to function without calling function?
[英]Create new Function and pass parameters without calling it
在項目中有實現的方法,它們將異步執行函數堆棧,但問題是,它們只接受函數,這是一個例子:
self.executeFunction = function(functionStackItem) {
// Some additional check and logics
// Some logging
functionProcessor.processFunction({
processableItem : functionStackItem
});
};
所以,我們有這樣的方法,用於創建將同步執行的函數:
userFunction = new Function('globalVariable, logger', userCode);
userFunction(globalVariable, logger);
但是現在,當我們轉向異步時我必須使用控制器提供的executeFunction方法,問題是,我不知道,我如何在這段代碼中添加這些參數:
userFunction = new Function('globalVariable, logger', userCode);
// userFunction(globalVariable, logger); cannot use this, because this will call and execute function immediately
projectName.processingController.executeFunction(userFunction); // passing function, that will be executed as needed, but it doesn't contain parameters
正如您在上面的代碼中看到的那樣,函數被傳遞,但是需要的參數:globalVariable和logger將是未定義的 - 我該如何修復它? 有沒有辦法不需要重新處理processingController?
你要么使用包裝函數:
projectName.processingController.executeFunction(function() {
return userFunction(globalVariable, logger);
});
或者如果this
是由executeFunction
設置為有意義的:
projectName.processingController.executeFunction(function() {
return userFunction.call(this, globalVariable, logger);
});
projectName.processingController.executeFunction(
userFunction.bind(null, globalVariable, logger)
);
......但如果executeFunction
設置this
東西有意義,因為bind
設置一個特定的this
(我用null
了這樣的說法以上)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.