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

前端之家收集整理的这篇文章主要介绍了javascript – Browserify:嵌套/有条件需求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在下面的CommonJS / Browserify模块中,如何避免每次导入foo和bar?而不是仅仅根据init()中的条件导入所需要的那个?
  1. var Foo = require('foo'),Bar = require('bar'),Component = function(config) {
  2. this.type = config.type;
  3. this.init();
  4. };
  5.  
  6. Component.prototype = {
  7.  
  8. init: function() {
  9. var instance = null;
  10.  
  11. switch (this.type) {
  12. case ('foo'):
  13. instance = new Foo(...);
  14. break;
  15. case ('bar'):
  16. instance = new Bar(...);
  17. break;
  18. }
  19. }
  20. };

解决方法

  1. Component = function(config) {
  2. this.type = config.type;
  3. this.init();
  4. };
  5.  
  6. Component.prototype = {
  7.  
  8. init: function() {
  9. var instance = null;
  10.  
  11. switch (this.type) {
  12. case ('foo'):
  13. instance = new (require('foo'))(...);
  14. break;
  15. case ('bar'):
  16. instance = new (require('bar'))(...);
  17. break;
  18. }
  19. }
  20. };

猜你在找的JavaScript相关文章