From d6cca750937a82ba58fd20d343d289324ef60bb9 Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Sat, 5 Mar 2011 23:11:13 -0500 Subject: [PATCH] Can now override toString() method of a class --- lib/class.js | 35 +++++++++++++++++++++-------------- test/test-class-extend.js | 26 ++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/lib/class.js b/lib/class.js index 85fa979..ec9e3cc 100644 --- a/lib/class.js +++ b/lib/class.js @@ -489,7 +489,7 @@ var extend = ( function( extending ) prototype.parent = base.prototype; // set up the new class - var new_class = createCtor( cname, abstract_methods ); + var new_class = createCtor( cname, abstract_methods, members ); attachPropInit( prototype, properties ); @@ -523,10 +523,11 @@ var extend = ( function( extending ) * * @param {string} cname class name (may be empty) * @param {Array.} abstract_methods list of abstract methods + * @param {Object} members class members * * @return {Function} constructor */ - function createCtor( cname, abstract_methods ) + function createCtor( cname, abstract_methods, members ) { // concrete class if ( abstract_methods.__length === 0 ) @@ -559,18 +560,24 @@ var extend = ( function( extending ) // constructor to ensure they are not overridden) attachInstanceOf( this ); - // provide a more intuitive string representation of the class - // instance - this.toString = ( cname ) - ? function() - { - return '[object #<' + cname + '>]'; - } - : function() - { - return '[object #]'; - } - ; + // Provide a more intuitive string representation of the class + // 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 ) + ? function() + { + return '[object #<' + cname + '>]'; + } + : function() + { + return '[object #]'; + } + ; + } }; // provide a more intuitive string representation diff --git a/test/test-class-extend.js b/test/test-class-extend.js index a82f61f..6a78ac0 100644 --- a/test/test-class-extend.js +++ b/test/test-class-extend.js @@ -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" + ); +} )(); +