在下面的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; } } };
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。