用Javascript中导入的库创建一个实用程序类

Creating an utility class with imported libraries in Javascript

本文关键字:一个 实用程序 创建 Javascript 导入      更新时间:2023-09-26

(我是javscript的新手,)我想创建一个可以访问网页上某些库的实用程序类。例如,我目前在我的网页上加载了D3和Jquery

<script src="http://d3js.org/d3.v3.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="util.js"></script>

我的实用程序类(utils.js)看起来像

(function (window, JQ, D3) {
    function hasWindow(){
        console.log(window);    
    }
    function hasJquery(){
        console.log(JQ);    
    }
    function hasD3(){
        console.log(D3);    
    }
})(this, this.jQuery, this.d3);

我有三个问题:

  1. 我需要传入库和窗口才能在其中使用它们吗util.js,还是它已经可以访问它们了
  2. 加载util.js后,如何调用实用程序类上的函数(即。hasWindow();)
  3. 我是否真的使用了一个合适的模式来创建实用程序类

如果所有库都加载到页面中,您就可以从自己的库中访问其他库。

最好等到页面加载完成后再加载。您可以在JQuery中使用$(function(){ ... });