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();


Google
 
Brett's Blog Web