-
-
Save carlosvillu/4077926 to your computer and use it in GitHub Desktop.
Safe extend to bypass constructors that throw Errors.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 () {/* Code */} } ); | |
* 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment