From 3f169d87ea6f6ade53dc8e769cb20bcd0383aa9c Mon Sep 17 00:00:00 2001 From: Mike Gerwitz Date: Sun, 14 Nov 2010 21:50:56 -0500 Subject: [PATCH] Refactored method override logic into its own function --- lib/class.js | 63 ++++++++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 24 deletions(-) diff --git a/lib/class.js b/lib/class.js index 57bd48d..fb195b8 100644 --- a/lib/class.js +++ b/lib/class.js @@ -172,31 +172,9 @@ function prop_copy( props, dest, result_data ) // check for method overrides else if ( ( pre !== undefined ) && ( pre instanceof Function ) ) { - // ensure we're overriding the method with another method - if ( !( prop instanceof Function ) ) - { - throw new TypeError( "Cannot override method with non-method" ); - } - - dest[ property ] = ( function( method, super_method ) - { - // this is the method that will be invoked when the requested - // method is called, so note that in the context of this - // function, `this` will represent the current class instance - return function() - { - var tmp = this.__super; - - // assign _super temporarily for the method invocation so - // that the method can call the parent method - this.__super = super_method; - var retval = method.apply( this, arguments ); - this.__super = tmp; - - return retval; - } - })( prop, dest[ property ] ); + dest[ property ] = method_override( pre, prop ); } + // just copy over the property else { dest[ property ] = prop; @@ -212,6 +190,42 @@ function prop_copy( props, dest, result_data ) } +/** + * Overrides a method + * + * The given method must be a function or an exception will be thrown. + * + * @param {Function} super_method method to override + * @param {Function} new_method method to override with + * + * @return {Function} overridden method + */ +function method_override( super_method, new_method ) +{ + // ensure we're overriding the method with another method + if ( !( new_method instanceof Function ) ) + { + throw new TypeError( "Cannot override method with non-method" ); + } + + // this is the method that will be invoked when the requested + // method is called, so note that in the context of this + // function, `this` will represent the current class instance + return function() + { + var tmp = this.__super; + + // assign _super temporarily for the method invocation so + // that the method can call the parent method + this.__super = super_method; + var retval = new_method.apply( this, arguments ); + this.__super = tmp; + + return retval; + } +} + + /** * Shrinks an array, removing undefined elements * @@ -422,3 +436,4 @@ function attach_extend( func ) // less restrictive) define_secure_prop( func, 'extend', ext_method ); } +