簡體   English   中英

JS封閉深度嵌套

[英]JS closures with deep nesting

NPM模塊有以下代碼:

var actions = {};
var methods = ['POST', 'GET', 'PATCH', 'DELETE'];

methods.forEach(function(method) {
  actions['mock' + method] = function(browser, url, response) {
    browser.execute(function() {
      result[method][url] = response;
    });
  }
});

module.exports = actions;

我想要4個方法:mockPOST,mockGET,mockDELETE,mockPATCH。 每個方法都應該只使用回調函數執行browser.execute並將response放在相應的result字段中 - result['POST']mockPOST ,依此類推。 但是當我執行時

utils.mockPOST(browser, 'auth', {"result": "OK"});

我得到的method is not defined錯誤。 我該怎么辦? 謝謝!

正如我所見,你正在為node.js使用selenium或webdriver。 這讓事情變得有點棘手。 你不能在browser.execute函數中使用閉包,原因是它根本不在那里運行。 Webdriver會將函數轉換為字符串,將其傳輸到瀏覽器,並在瀏覽器中eval該字符串。 nodejs閉包不會傳遞給瀏覽器,只會將函數代碼作為字符串傳遞。

我假設result對象已經在瀏覽器中全局定義。

所以你對此能做些什么? 我總是建議不要將函數文字放在browser.executebrowser.executeAsync因為它們令人困惑。 你可以在那里放一個字符串,它將被評估。 請嘗試以下方法:

methods.forEach(function(method) {
  actions['mock' + method] = function(browser, url, response) {
    var browserAction = "result[" + JSON.stringify(method) + "]" +
        "[" + JSON.stringify(url) + "] = " +
        JSON.stringify(response) + ";";
    browser.execute(browserAction);
  };
});

暫無
暫無

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

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