Fresh prototypes on all browsers

So there’s a well known technique for getting Object prototypes that are not from the current window which results in a fresh prototype. You use iframes to copy the required prototype from the iframe.contentWindow BUT…It doesn’t work in all browsers and it’s pretty silly having to copy each object manually, why not just use the window? Well you can 😀

So after a lot of code testing/rewriting here is how to do it:-

var iframe = document.createElement('iframe');				
iframe.style.width = '1px';
iframe.style.height = '1px';
iframe.frameborder = "0";
iframe.style.position = 'absolute';
iframe.style.left = '-100px';
iframe.style.top = '-100px';				
document.body.appendChild(iframe);
var code = "(function(objConstructor){ return window.NameOfInstance= objConstructor();})(" + objConstructor+ ")";									
if (window.opera) {
	iframe.contentWindow.Function(code)();
} else {
	iframe.contentWindow.document.write('<\script type="text/javascript">' + code + '<\/script>');
	iframe.contentWindow.document.close();
}
var obj = iframe.contentWindow.NameOfInstance;	
if(!obj) {
	iframe.contentWindow.Function(code)();
	obj = iframe.contentWindow.NameOfInstance;
}	

So here obj contains our Object instance within the context of the iframe window, that means any references to window inside your object only affect the iframe context. The reason for the if statements and different code is because Firefox, Safari, Opera and IE all act differently. Opera doesn’t pass the object straight away unless the Function constructor is used, Safari supports the Function constructor method and the document.write method but doesn’t return the object correctly when using document.write until it’s loaded.

The important part about this code is that you don’t need to use the onload event of the iframe as the object is returned instantly 🙂

Comments are closed :( too much spam. If you want to contact me about any article please email or tweet me.