1
0
Fork 0

Began adding Class.extend()

closure/master
Mike Gerwitz 2010-11-10 18:40:36 -05:00
parent 979331cda3
commit 8d6c2645bc
2 changed files with 63 additions and 8 deletions

View File

@ -31,21 +31,62 @@ var Class = function()
}; };
exports.extend = function() /**
* Mimics class inheritance
*
* This method will mimic inheritance by setting up the prototype with the
* provided base class (or, by default, Class) and copying the additional
* properties atop of it.
*
* The class to inherit from (the first argument) is optional. If omitted, the
* first argument will be considered to be the properties list.
*
* @return {Object} extended class
*/
var extend = function()
{ {
Class.prototype.extend.apply( this, arguments ); var args = Array.prototype.slice.call( arguments ),
props = args.pop() || {},
base = args.pop() || Class,
prototype = new base(),
new_class = function() {};
new_class.prototype = prototype;
return new_class;
} }
/**
* Creates a class, inheriting either from the provided base class or the
* default base class
*
* @param {Object} base object to extend (extends Class by default)
*
* @return {Object} extended class
*/
exports.extend = function( base )
{
return extend.apply( this, arguments );
}
/**
* Shorthand for extending classes
*
* This method can be invoked on the object, rater than having to call
* Class.extend( this ).
*
* @param {Object} props properties to add to extended class
*
* @return {Object} extended class
*/
Object.defineProperty( Class.prototype, 'extend', Object.defineProperty( Class.prototype, 'extend',
{ {
value: function() value: function( props )
{ {
var args = Array.prototype.slice.call( arguments ), return extend( this, props );
props = args.pop() || {},
base = args.pop() || Class;
var prototype = new this();
}, },
enumerable: false, enumerable: false,

View File

@ -31,3 +31,17 @@ assert.ok(
"Class module should provide an 'extend' method" "Class module should provide an 'extend' method"
); );
// create a basic test class
var Foo = Class.extend();
assert.ok(
( Foo instanceof Object ),
"Extend method creates a new object"
);
assert.ok(
( Foo.prototype.extend instanceof Function ),
"Created class contains extend method in prototype"
);