1

I'm trying to get my head around protoypal inheritance and have a question about shared member variables.

I have an object:

var objA = {
    list: [],
    myPush: function(aParam){
      this.list.push(aParam);
    }
}

and try to "protoypal inherit" it with the object() function from http://javascript.crockford.com/prototypal.html

var objB = object(objA);

but somehow a change to objA gets transfered to objB:

objA.myPush('a string');
equals(objA.list.length, 1);
equals(objB.list.length, 0); //<= Fails. Why?

The full code with failing tests: http://jsbin.com/izawi/edit

Could someone explain this to me? And possible fixes. I could have an constuct() function, but this doesn't seems right.

Thanks in advance

Matthias

luebken
  • 6,221
  • 5
  • 22
  • 18

1 Answers1

1

As exposed in an earlier thread, Crockford's object function is slightly broken. Let me see if I can find the SO thread in question.

The "traditional" Constructor inheritence works:

var a = {
    list: [],
    myPush: function(aParam){
      this.list.push(aParam);
    }
}

function B () {}
B.prototype = a;

var b = new B();
a.myPush('a string');

b.list.length == a.list.length; // true

This is slightly less pure than "proper" prototypal inheritance - Constructors inherit from objects instead of objects inherit from objects. Yes, it somehow doesn't feel right to me too. And no, I can't quite explain why Crockford's object function fails in this. It's just the way the world works I guess.

update: Here's the related discussion I was thinking of: Implementing instance methods/variables in prototypal inheritance

Community
  • 1
  • 1
slebetman
  • 109,858
  • 19
  • 140
  • 171
  • Thanks for the pointer. Interestingly yours and the other pointer use a solution against Crockfords recommendation. Kind of hard for newcomer to decide. – luebken Feb 01 '10 at 14:07