[Project_owners] JavaScript prototype question

Aaron Boodman zboogs at gmail.com
Tue Dec 6 11:45:34 EST 2005


Only constructor functions can have .prototype. The value of
.prototype flows through instances of that constructor as private
internal data of the JSObject which JavaScript code cannot (usually)
access.

 So the canonical way to do multi-level inheritance is:

function A() {}

A.prototype = new B();

function B() {}

B.prototype = {}; // or new C...


One reason this sucks is that it creates an instance of B when that
isn't what you really meant.

Luckily, Mozilla has a cool syntax you can use to circumvent this problem:

function A() {}
A.prototype.foo = function(){}

function B(){}
B.prototype = {};
B.prototype.__proto__ = A.prototype;
B.prototype.bar = function(){}

var b = new B();
b.foo();
b.bar();

You can encapsulate this a bit with:

function clone(parent) {
  var obj = {};
  obj.__proto__ = parent;
  return obj;
}

function B(){}
B.prototype = extend(A.prototype);
B.prototype.bar = function(){}

- a

On 12/6/05, Adam Judson <adamsplugins at gmail.com> wrote:
> I thought I understood this...
>
> I have
>
> function A() = ...
>
> A.prototype = {...}
>
> and now I want to add
>
> A.prototype.prototype = new SuperClass();
>
> which doesn't do what I want.
>
> Is there a way to do this?
>
> Adam
> _______________________________________________
> Project_owners mailing list
> Project_owners at mozdev.org
> http://mozdev.org/mailman/listinfo/project_owners
>


More information about the Project_owners mailing list