Can now override toString() method of a class
parent
dfa2966d99
commit
d6cca75093
35
lib/class.js
35
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.<string>} 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 #<anonymous>]';
|
||||
}
|
||||
;
|
||||
// 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 #<anonymous>]';
|
||||
}
|
||||
;
|
||||
}
|
||||
};
|
||||
|
||||
// provide a more intuitive string representation
|
||||
|
|
|
@ -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"
|
||||
);
|
||||
} )();
|
||||
|
||||
|
|
Loading…
Reference in New Issue