1

我正在移植我的一个旧 javascript 文件以与 requireJS 兼容。这是以前代码的样子。

// 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();
})

上面的代码不会运行,我如何通过运行 effect('box').run() 的简写来达到相同的结果。

4

1 回答 1

2

试试这个:

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();
});
于 2012-04-30T12:34:35.377 回答