开发者

How to initialize member variables in JavaScript with protoypal inheritance

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 wi开发者_开发知识库th 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜