Adrien Cadet
Adrien Cadet

Reputation: 1341

Load Classes with RequireJS

I have a question about RequireJS and JS OOP. I would like to have one class per file and define dependencies inside this one. For the moment, I'm using require method and define class into callback function but I can't reach my class elsewhere. I tried to define my class as a window's attribute but it still doesn't work.

Do you have an idea? Else, if you have a better way to manage classes like you can do in JAVA or other OO languages, I would appreciate :)

I thank you in advance!

Upvotes: 0

Views: 612

Answers (1)

Louis
Louis

Reputation: 151401

(Keeping in mind that when we create "classes" in JavaScript we're really simulating a class system with JavaScript's prototype system...)

Here's an example of a trivial class that can be accessed from outside:

define(function (require, exports, module) {
'use strict';

function ParamError(message) {
    this.message = message;
}

ParamError.prototype.toString = function () {
    return this.message;
};

exports.ParamError = ParamError;
});

Supporing the code above is in a file named errors.js and is accessible to RequireJs, if I want to use it elsewhere:

define(function (require, exports, module) {
'use strict';

var errors = require("errors");

var foo = new errors.ParamError("blah");

// Here is a simple illustration of how it can be extended.

function NewError() {
    ParamError.call(this, arguments);
}

NewError.prototype = new errors.ParamError();

});

Upvotes: 1

Related Questions