簡體   English   中英

創建新函數並傳遞參數而不調用它

[英]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);
});

Function#bind

projectName.processingController.executeFunction(
    userFunction.bind(null, globalVariable, logger)
);

......但如果executeFunction設置this東西有意義,因為bind設置一個特定的this (我用null了這樣的說法以上)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM