这个javascript函数在做什么?

这是我需要修改的前承包商编写的代码摘录。我迷失在 ({function (e)}) 和闭包中。


该代码向验证服务器发出 http 请求并返回一个令牌,该令牌设置了 myPlugin 对象的成员变量 (r = e)。然后,该函数将 foobar.js 动态加载到附加到 head 标记的新脚本标记中。foobar.js 中的代码引用了 myPlugin 对象的 getter 函数。


我只需要删除 http 请求和回调并传递一个参数来设置 r 的值并将新的脚本标记附加到 head 标记。


每次我尝试修改 loadPluginJsFn 函数时都会出错。


谁能解释 loadPluginJsFn 函数在做什么以及“(myPlugin);”的目的是什么?在 foobar.js 的末尾和 myPlugin 对象末尾的 () ?


HTML文件

var myPlugin = (function() {

  var t, n, r, o_value ;

  return {

    set somevalue(e) {

      o_value = e;

    },

    get somevalue() {

      return o_value;

    },

    init(config){


    },

// This is where I don't understand what it happening

    loadPluginJsFn: function(e) {

      "function" == typeof e &&

        e(function(e) {

          e &&

            ((r = e),

            (function(e) {

              var t = document.createElement("script");

              (t.type = "text/javascript"),

                (t.src = e),

                document.querySelector("head").appendChild(t);

            })(

              "js/foobar.js"

            ));

        });

    }

  };

})();


myPlugin.loadPluginJsFn(function(callback) {

  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {

      callback(xhr.responseText);

    }

  };

  xhr.open("GET", "<some domain>", true);

});

foobar.js

(function (my_Plugin) {


    const somevars = 'xxx';

    var   someMoreVars = '123'


  function somefunctions(useDefaults = false) {

    return somethingImportant;

  }


})(myPlugin);


拉丁的传说
浏览 137回答 2
2回答

温温酱

事实证明,删除代码比添加代码容易得多。感谢@cucaracho 和@barmar 提供重要见解。这是我想出的解决方案。我不再需要 AJAX 调用了——这就是我想要删除的。从 loadPluginJsFn 中删除回调被证明是一个挑战。我打扫了房子并确认它仍然正常运行。loadPluginJsFn(token) {&nbsp; &nbsp; &nbsp; r = token,&nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; doc = document.createElement("script");&nbsp; &nbsp; &nbsp; doc.type = "text/javascript";&nbsp; &nbsp; &nbsp; doc.src = "js/foobar.js";&nbsp; &nbsp; &nbsp; document.querySelector("head").appendChild(doc);}

梦里花落0921

这是将该函数翻译成更易读的代码:loadPluginJsFn: function(cb) {&nbsp; if (typeof cb == "function") {&nbsp; &nbsp; cb(function(response) {&nbsp; &nbsp; &nbsp; if (response) {&nbsp; &nbsp; &nbsp; &nbsp; r = response;&nbsp; &nbsp; &nbsp; &nbsp; // Load the script from foobar.js&nbsp; &nbsp; &nbsp; &nbsp; var url = "js/foobar.js";&nbsp; &nbsp; &nbsp; &nbsp; var t = document.createElement("script");&nbsp; &nbsp; &nbsp; &nbsp; t.type = "text/javascript";&nbsp; &nbsp; &nbsp; &nbsp; t.src = url;&nbsp; &nbsp; &nbsp; &nbsp; document.querySelector("head").appendChild(t);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; }}cb将是执行 AJAX 请求的函数<some domain>。收到响应后,它会调用function(response)。这将插件变量r设置为响应,然后加载js/foobar.js脚本。foobar.js然后执行使用该MyPlugin对象的代码(我假设您忽略了这些细节),并且该代码大概使用r.总结:这从<some domain>使用 AJAX 中获取一个值,将其放入 中的r变量中MyPlugin,然后运行使用该插件的代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript