Put your message here! Contact me for more information
 
 








 

I was working on Stripe Designer and this nasty bug of null object kept on bugging me in IE. In Firefox, the code works so well (both FireBug and the invaluable Web Developer bar did not give any warning/ error) but in IE, the thing just crash.

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];
}


 

2 Responses to “SitePoint Blogs » Javascript Inheritance bug and fix



troelskn
2:34 am
July 21, 2006
#61

I’m using the implementation in :
http://www.itsalleasy.com/2006/02/05/prototype-chain/




4:14 am
April 10, 2007
#22770

There is another approach to implement JavaScript inheritance - a “lazy” inheritance which has all benefits of “prototype” based approach like typed classes, but also eliminates necessity to declare external scripts in proper order and automatically resolves and loads (if necessary) dependencies to external scripts that contains related classes.
This approach is supported by JSINER library - you can find more about it on http://www.soft-amis.com/jsiner/inheritance.html




 

Leave a Reply