Skip to content

Instantly share code, notes, and snippets.

@tcorral
Created November 15, 2012 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tcorral/4077753 to your computer and use it in GitHub Desktop.
Save tcorral/4077753 to your computer and use it in GitHub Desktop.
Safe extend to bypass constructors that throw Errors.
/**
* This piece of code has been created to safely extend classes/objects in Javascript.
* After talk with a great friend that was upset trying to extend a class/object that throws an error
* if some parameter in the constructor of the class/object is missing.
*
* var Search = function ( sToSearch ) {
* if ( sToSearch == null ) { // Check if sToSearch is null or undefined
* throw new Error( 'Search needs a string to search' );
* }
* this.sToSearch = sToSearch;
* this.sType = 'Parent';
* // More code
* };
* Search.prototype.whatToSearch = function () {
* alert( this.sToSearch );
* };
*
* If we try a classic prototypal inheritance we will get an error:
*
* var SearchInherited = function ( sToSearch ) {
* Search.call( this, sToSearch );
* this.sType = 'Child';
* };
* Search.prototype = new Search();
* Search.prototype.whatToSearch = function () {
* alert( 'Child what to Search: ' + this.sToSearch );
* };
* The solution is extend the prototype using the constructor.
* See the code to understand it beeter.
*/
/**
* Usage:
* var Child = safeExtend( Parent, { property1: value, method1: function () { } } );
* After this you will have a Child class/object that extends from Parent.
*/
function safeExtend(oParent, oOverwiteInstanceProperties) {
var oP, sKey;
function F() {
oParent.apply( this, arguments ); // Inherit the constructor members.
// Set a parent reference to access to parent methods.
this.parent = oParent.prototype;
// Set the instance properties for the Child.
// @TODO if oOverwriteInstanceProperties is a function execute it with F as context.
for ( sKey in oOverwiteInstanceProperties ) {
if ( oOverwiteInstanceProperties.hasOwnProperty( sKey ) ) {
this[sKey] = oOverwiteInstanceProperties[sKey];
}
}
};
F.prototype = new oParent.constructor();
return F;
};
@carlosvillu
Copy link

Tengo una duda, como puedo a su vez tener validaciones y lanzar exceptions en el constructor de la clase hija ?!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment