如何将这段代码写的更像是封装起来的模块,我这样写应该怎样优化,比如:希望该方法只剩成一个实例对象

这是一个自己写的创建div的方法,想要模块话,不知道这样写有没有优化的空间,比如,希望该方法只剩成一个实例对象,如何避免将暴露出来的modules的init被重写,现在里面的方法之间也没有很好的解耦

 let modules = (function(w, $) {
        let mod = {};
        let rootDom = $("#wl-extend");
        let className = rootDom.attr("class");
        let getClassNameDom = function() {
          let _c = className.split(" ");
          if (_c[0].indexOf("wl-extend") > -1) {
            let _dom = _c[0].split("-");
            return _dom[2];
          } else {
            throw "未获取需要创建的dom元素";
          }
        };
        mod.init = function(obj) {
          let color = obj.color || "red";
          let colorbor = obj.borderColor || "#ccc";
          let width = obj.width || "200px";
          let height = obj.height || "50px";
          let domName = getClassNameDom();
          createDom(domName, color, colorbor, width, height);
        };
        let createDom = function(domName, color, colorbor, width, height) {
          rootDom.html(`<${domName} id='wl-create-dom'></${domName}>`);
          let childrenDom = $("#wl-create-dom");
          childrenDom.css({
            color: color,
            border: `1px solid ${colorbor}`,
            width: width + "px",
            height: height + "px"
          });
          $("#wl-extend").append(childrenDom);
        };
        return mod;
      })(window, jQuery);

      $(function() {
        modules.init({
          width: 500,
          height: 200,
          borderColor: "red"
        });
      });
阅读 654
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题