javascript – Browserify:嵌套/有条件需求

前端之家收集整理的这篇文章主要介绍了javascript – Browserify:嵌套/有条件需求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的CommonJS / Browserify模块中,如何避免每次导入foo和bar?而不是仅仅根据init()中的条件导入所需要的那个?
var Foo = require('foo'),Bar = require('bar'),Component = function(config) {
  this.type = config.type;
  this.init();
};

Component.prototype = {

  init: function() {
    var instance = null;

    switch (this.type) {
      case ('foo'):
        instance = new Foo(...);
        break;
      case ('bar'):
        instance = new Bar(...);
        break;
    }
  }
};

解决方法

Component = function(config) {
  this.type = config.type;
  this.init();
};

Component.prototype = {

  init: function() {
    var instance = null;

    switch (this.type) {
      case ('foo'):
        instance = new (require('foo'))(...);
        break;
      case ('bar'):
        instance = new (require('bar'))(...);
        break;
    }
  }
};
原文链接:https://www.f2er.com/js/152521.html

猜你在找的JavaScript相关文章