After much cursing and banging on my keyboard, I have found the little nasty bug… But first, let’s me give you original the code snippet from SitePoint that enables simple inheritance in Javascript
function copyPrototype(descendant, parent) {
var sConstructor = parent.toString();
var aMatch = sConstructor.match( /\s*function (.*)\(/ );
if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; }
for (var m in parent.prototype) {
descendant.prototype[m] = parent.prototype[m];
}
};
[[http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance|From SitePoint Blogs » Javascript Inheritance]]
The code fails in IE as the regexp that is used to match the contrucstor will also match anything after “function ” (one space after function) and the left paranthesis. This means if I write …
function Dog ( ...
then the result of the match is “Dog “. In Firefox, this works fine. However, in IE, things just stop working without any good hints on why and where the broken point is. ScriptDebugger didn’t work too well either. Anyway, the solution is simply trimming the spaces after and before the match. To do that, modify descendant.prototype[aMatch[1]] = parent; to descendant.prototype[aMatch[1].replace(/^\s*|\s*$/g,"")] = parent;
For your convenience, here is the readily available code for you to use…
function copyPrototype(descendant, parent) {
var sConstructor = parent.toString();
var aMatch = sConstructor.match( /\s*function (.*)\s*\(/ );
var sConstructor = parent.toString();
var aMatch = sConstructor.match( /\s*function (.*)\(/ );
if ( aMatch != null ) { descendant.prototype[aMatch[1].replace(/^\s*|\s*$/g,"")] = parent; }
descendant.prototype[ aMatch[1] ] = parent;
for (var m in parent.prototype)
descendant.prototype[m] = parent.prototype[m];
}
I’m using the implementation in :
http://www.itsalleasy.com/2006/02/05/prototype-chain/