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

1 Answer 1

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

1
  • Thanks for the pointer. Interestingly yours and the other pointer use a solution against Crockfords recommendation. Kind of hard for newcomer to decide.
    – luebken
    Commented Feb 1, 2010 at 14:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.