Javascript 如何使此模块与requireJS兼容
我正在将我的一个旧javascript文件移植到与requireJS兼容的程序中。这是以前代码的样子Javascript 如何使此模块与requireJS兼容,javascript,requirejs,Javascript,Requirejs,我正在将我的一个旧javascript文件移植到与requireJS兼容的程序中。这是以前代码的样子 // effect.js (function(exports){ // shorthand exports.effect = function(selector) { return new Effect(selector); }; // init exports.Effect = function(selector){
// effect.js
(function(exports){
// shorthand
exports.effect = function(selector) {
return new Effect(selector);
};
// init
exports.Effect = function(selector){
this.target = document.getElementById(selector);
};
Effect.prototype.run = function(){
alert('halo');
};
})(this);
//invoke it with
effect('box').run();
试图使其与requireJS兼容:
// effect.js
define(function(exports){
// Shorthand
exports.effect = function(selector) {
return new Effect(selector);
};
// init
exports.Effect = function(selector){
alert('halo');
this.target = document.getElementById(selector);
};
Effect.prototype.run = function(){
alert('halo');
};
}
// require js
require([
'effect.js'
],function(Effect){
effect('box').run();
})
上面的代码不会运行,我如何通过运行效果速记('box')获得相同的结果。run()。尝试一下:
define(function() {
// init
var Effect = function(selector) {
this.target = document.getElementById(selector);
};
Effect.prototype.run = function(){
alert('halo');
};
// Replaces the 'shorthand' function from the first example
// This is returned as a module to the require call
return function(selector) {
return new Effect(selector);
}
});
require(['effect.js'], function(effect) {
effect('box').run();
});
如果答案令人满意,请接受,或者强调您需要帮助的其他问题,干杯:)