【问题标题】:Split ES6 Class in multiple files to import individual methods of a library在多个文件中拆分 ES6 类以导入库的各个方法
【发布时间】:2021-02-25 15:59:36
【问题描述】:

假设我为辅助方法构建了一个库类。 我有一个包含字符串 utils 的文件,一个包含 ajax utils 的文件等等。

主类看起来像这样:

// helperUtils.js
export class helperUtils {
  constructor() {}

  basicHelperFn() {
    return true;
  }
}

现在我有一个导出这些字符串工具的文件:

// helperUtils/stringUtils.js
import { helperUtils } from '../helperUtils.js';

helperUtils.prototype = { 
  stringUtil1 : (str) => { 
    return str += ' this is very helpful!';
  }
}

export const stringUtils = helperUtils.prototype;
// more files...
// helperUtils/ajaxUtils.js
// helperUtils/objUtils.js
// ...

我现在如何导入主类并扩展它,仅将一些原型方法拆分为多个文件,例如仅导入字符串 utils。

import { helperUtils } from './helperUtils';
import { stringUtils} from './helperUtils/stringUtils';

const helper = new helperUtils();
helper.basicHelperFn();
helper.stringUtil1();

【问题讨论】:

    标签: javascript class inheritance ecmascript-6 prototype


    【解决方案1】:

    这样的?

    /*
     helperUtils/stringUtils.js 
    */
    import { helperUtils } from '../helperUtils.js';
    
    class StringUtils extends helperUtils {
        super();
        constructor() {}
        stringUtilNew(x) {
             /*
              Do somthing...
              */
             return x;
        }
    }
    
    export StringUtils;

    【讨论】:

    • 不应该在构造函数或其他方法中调用 super() 吗?加上使用扩展类,我必须调用孩子来访问这些方法,对吧?
    【解决方案2】:

    我做了更多的实验:

    这就是我现在想出来的:

    // helperUtils/stringUtils.js
    import { helperUtils } from '../helperUtils.js';
    
    helperUtils.prototype.stringUtil1 = (str) => { 
        return str += ' this is very helpful!';
    }
    
    export const stringUtils = helperUtils.prototype;
    

    现在 stringUtils 原型不会覆盖我的 helperUtils 原型,我可以安全地将单个方法导入我的主类。

    如果有人有更好的解决方案,请与我们分享!

    到目前为止谢谢!

    【讨论】:

      【解决方案3】:

      如果你的 stringUtils 类 extends helperUtils 类:

      // helperUtils/stringUtils.js
      import { helperUtils } from '../helperUtils.js';
      
      class StringUtils extends helperUtils {
          stringUtil1(str) {
               return str += ' this is very helpful!';
          }
      }
      
      export StringUtils;
      

      然后你可以简单地导入它并使用它。

      【讨论】:

      • 那个super()放错地方了,可以删除它和构造函数。
      • 谢谢。修复它
      猜你喜欢
      • 2017-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-13
      • 1970-01-01
      • 2019-08-21
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多