1
0
Fork 0

Can now override toString() method of a class

closure/master
Mike Gerwitz 2011-03-05 23:11:13 -05:00
parent dfa2966d99
commit d6cca75093
2 changed files with 47 additions and 14 deletions

View File

@ -489,7 +489,7 @@ var extend = ( function( extending )
prototype.parent = base.prototype; prototype.parent = base.prototype;
// set up the new class // set up the new class
var new_class = createCtor( cname, abstract_methods ); var new_class = createCtor( cname, abstract_methods, members );
attachPropInit( prototype, properties ); attachPropInit( prototype, properties );
@ -523,10 +523,11 @@ var extend = ( function( extending )
* *
* @param {string} cname class name (may be empty) * @param {string} cname class name (may be empty)
* @param {Array.<string>} abstract_methods list of abstract methods * @param {Array.<string>} abstract_methods list of abstract methods
* @param {Object} members class members
* *
* @return {Function} constructor * @return {Function} constructor
*/ */
function createCtor( cname, abstract_methods ) function createCtor( cname, abstract_methods, members )
{ {
// concrete class // concrete class
if ( abstract_methods.__length === 0 ) if ( abstract_methods.__length === 0 )
@ -559,8 +560,13 @@ var extend = ( function( extending )
// constructor to ensure they are not overridden) // constructor to ensure they are not overridden)
attachInstanceOf( this ); attachInstanceOf( this );
// provide a more intuitive string representation of the class // Provide a more intuitive string representation of the class
// instance // instance. If a toString() method was already supplied for us,
// use that one instead.
if ( !( Object.prototype.hasOwnProperty.call(
members[ 'public' ], 'toString'
) ) )
{
this.toString = ( cname ) this.toString = ( cname )
? function() ? function()
{ {
@ -571,6 +577,7 @@ var extend = ( function( extending )
return '[object #<anonymous>]'; return '[object #<anonymous>]';
} }
; ;
}
}; };
// provide a more intuitive string representation // provide a more intuitive string representation

View File

@ -281,3 +281,29 @@ for ( var i = 0; i < class_count; i++ )
} }
} )(); } )();
/**
* We provide a useful default toString() method, but one may wish to override
* it
*/
( function testCanOverrideToStringMethod()
{
var str = 'foomookittypoo',
result = ''
;
result = Class( 'Foo',
{
toString: function()
{
return str;
}
})().toString();
assert.equal(
result,
str,
"Can override default toString() method of class"
);
} )();