在下面的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;
- }
- }
- };