Modules – AMD Example
by Joshua McNeese
HTML
<script src="https://requirejs.org/docs/release/2.1.20/minified/require.js"></script>
JavaScript
define('canine', [], function () {
function Canine(name) {
this.name = name;
this.howler = true;
}
Canine.prototype.bark = function () {
return this.name + ' says: ' + (this.howler ? 'woooooow!' : 'woof, woof!');
};
return Canine;
});
define('dog', ['canine'], function (Canine) {
function Dog(name, breed) {
Canine.call(this, name);
this.breed = breed;
this.howler = breed === 'husky';
}
Dog.prototype = Object.create(Canine.prototype);
return Dog;
});
define('wolf', ['canine'], function (Canine) {
function Wolf(name) {
Canine.call(this, name);
}
Wolf.prototype = Object.create(Canine.prototype);
return Wolf;
});
define('animals', ['wolf', 'dog'], function (Wolf, Dog) {
return {
Dog: Dog,
Wolf: Wolf
};
});
require(['animals'], function (Animals) {
var wolf1 = new Animals.Wolf('Ghost');
console.log(wolf1.bark());
var dog1 = new Animals.Dog('Bandit', 'husky');
console.log(dog1.bark());
var dog2 = new Animals.Dog('Patches', 'healer');
console.log(dog2.bark());
});