Began adding Class.extend()
parent
979331cda3
commit
8d6c2645bc
57
lib/class.js
57
lib/class.js
|
@ -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',
|
||||
{
|
||||
value: function()
|
||||
value: function( props )
|
||||
{
|
||||
var args = Array.prototype.slice.call( arguments ),
|
||||
props = args.pop() || {},
|
||||
base = args.pop() || Class;
|
||||
|
||||
var prototype = new this();
|
||||
return extend( this, props );
|
||||
},
|
||||
|
||||
enumerable: false,
|
||||
|
|
|
@ -31,3 +31,17 @@ assert.ok(
|
|||
"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"
|
||||
);
|
||||
|
|
Loading…
Reference in New Issue