RequireJS: How to define modules that contain a single “class”?

后端 未结 2 1974
情深已故
情深已故 2020-11-28 19:40

I have a number of JavaScript \"classes\" each implemented in its own JavaScript file. For development those files are loaded individually, and for production they are conca

2条回答
  •  星月不相逢
    2020-11-28 20:27

    As an addition to jrburke's answer, note that you don't have to return the constructor function directly. For most useful classes you'll also want to add methods via the prototype, which you can do like this:

    define('Employee', function() {
        // Start with the constructor
        function Employee(firstName, lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }
    
        // Now add methods
        Employee.prototype.fullName = function() {
            return this.firstName + ' ' + this.lastName;
        };
    
        // etc.
    
        // And now return the constructor function
        return Employee;
    });
    

    In fact this is exactly the pattern shown in this example at requirejs.org.

提交回复
热议问题