Skip to content

Instantly share code, notes, and snippets.

@bennadel
Created January 26, 2012 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennadel/1683287 to your computer and use it in GitHub Desktop.
Save bennadel/1683287 to your computer and use it in GitHub Desktop.
Extending Classes In A Modular JavaScript Application Architecture Using RequireJS
// Define the Friend model class. This extends the core Model.
define(
[
"./model"
],
function( Model ){
// I return an initialized object.
function Friend( name ){
// Call the super constructor.
Model.call( this );
// Store the name.
this._name = name;
// Return this object reference.
return( this );
}
// The Friend class extends the base Model class.
Friend.prototype = Object.create( Model.prototype );
// Define the class methods.
Friend.prototype.getName = function(){
return( this._name );
};
// -------------------------------------------------- //
// -------------------------------------------------- //
// Return the base Friend constructor.
return( Friend );
}
);
// Load the application.
require(
[
"./model/friend"
],
function( Friend ){
// Create a few instances of Friend so that we can see
// how inherited functionality has been propogated.
var friends = [
new Friend( "Sarah" ),
new Friend( "Tricia" ),
new Friend( "Joanna" )
];
// Now, iterate over each friend to output the name (which
// is part of the FRIEND class) and the ID (which is part of
// the inhereted MODEL class).
for (var i = 0 ; i < friends.length ; i++){
console.log(
friends[ i ].getName(),
":",
friends[ i ].getInstanceID()
);
}
}
);
// Define the base / core Model class.
define(
function(){
// I am the internal, static counter for the number of models
// that have been created in the system. This is used to
// power the unique identifier of each instance.
var instanceCount = 0;
// I get the next instance ID.
var getNewInstanceID = function(){
// Precrement the instance count in order to generate the
// next value instance ID.
return( ++instanceCount );
};
// -------------------------------------------------- //
// -------------------------------------------------- //
// I return an initialized object.
function Model(){
// Store the private instance id.
this._instanceID = getNewInstanceID();
// Return this object reference.
return( this );
}
// I return the current instance count. I am a static method
// on the Model class.
Model.getInstanceCount = function(){
return( instanceCount );
};
// Define the class methods.
Model.prototype = {
// I return the instance ID for this instance.
getInstanceID: function(){
return( this._instanceID );
}
};
// -------------------------------------------------- //
// -------------------------------------------------- //
// Return the base Model constructor.
return( Model );
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment