Brett's Blog
Edit     New

Thursday, March 19, 2009

Observations on prototype

Came across the following interesting prototype behavior while trying to define methods on the class conditionally (for use in a large library where one might only wish to add certain groups of functions to the prototype, but which would be fine and memory-friendly for any instance which did want to use them).

function A () {
// this.prototype.b = function () {alert('c');}; // this.prototype is undefined
this.prototype = {b:function () {alert('c');}}; // rewrites prototype, but doesn't behave like a prototype, since by using 'this', we're creating our own copy; we can of course call items on the prototype but by dropping the word 'prototype'
this.__proto__ = {c:function () {alert('d');}}; // Mozilla only; works as probably intended
// A.prototype.b = function () {alert('e');}; // will work but requires hard-coding the class name here

var z = new A();
z.prototype.b(); // 'c'
z.c(); // 'd'
z.b(); // 'z.b is not a function' error

If your purpose in trying something like I was to conditionally add functions to the prototype (and thus for use by all instances), use of a static method on A() might be a better approach since it wouldn't involve building a large function into memory each time.

On another subject, here's I think a helpful way to distinguish between prototype and __proto__ in Mozilla:

function a () {
this.b = function () {alert('our own b');};
this.__proto__.b(); // 'prototype b' (this only works in Mozilla)
this.b(); // 'our own b' (we've covered b() on our prototype, though it is still there)
a.prototype.b = function () {alert('prototype b');};

var z = new a();

or to build on this example, a little:

function a () {
this.b(); // 'prototype b'

this.b = function () {alert('our own b');};
this.__proto__.b(); // 'prototype b' (this only works in Mozilla)
this.b(); // 'our own b' (we've temporarily covered b() on our prototype)

delete this.b;
this.b(); // now we get 'prototype b' again
a.prototype.b = function () {alert('prototype b');};

var z = new a();


  • Hey Brett,

    Sorry, this hasn't got anything to do with your blog, but instead I saw you edited the mdc page about liveconnect and I hoped you might be able to help me with a problem I'm having with security permissions!

    Basically I can run a basic java class from firefox, but haven't been able to get code I grabbed from Java Firefox Extension to give me security permissions and so can't read or write files etc.

    I've got a thread/post about it on the sun forums here.

    If it's not too much trouble do you think you could post the simplest code required to give an extension all java permissions?! I'd be very grateful!

    My email address is just my name at

    Apologies again for gatecrashing your blog, hope you don't mind!


    By Anonymous mzatanoskas, at Tuesday, 31 March, 2009  

Post a Comment

Links to this post:

Create a Link

<< Home

Brett's Blog Web