Hi,
> My Test Code:
>
> var base = Class.create({
> collection: [],
> itterations:0,
> initialize: function() {
> this.itterations++;
> this.collection.push(this.itterations);
> console.log('Itterations: %s, Number items in Collection: %s',
> this.itterations, this.collection.size());
> }
>
> });
What that does is create a constructor function where `collection` is
shared by all instances created by the function, because `collection`
is part of the constructor's prototype. This is correct behavior. It
happens because you never assign to `collection` via one of your
instances, so the instances (including the ones that are the
prototypes for `foo` and `bar`) continue to use the prototype's copy.
It's the same mechanism that allows function objects to be shared. (It
would happen if collection were some other kind of object reference,
too.) In class-based OOP you'd think of it as being a class member.
> var foo = Class.create(base, {});
> var bar = Class.create(base, {});
Your derived constructor functions also share `collection` because
they're using it from the base constructor's prototype, too. There is
only one `collection` array in total, no matter how many derived
constructors or new instances you create. (There's no real analogue in
class-based OOP here, I don't think. Prototypical OOP is just
different sometimes.)
Victor's solution moves `collection` to the `foo` and `bar`
constructor function prototypes instead, and so all `foo` instances
will share the `foo` constructor's collection, and all `bar` instances
will share the `bar` constructor's collection. If that's what you
meant, great.
But if you want each *instance* to have its own collection, which is
the normal use-case, initialize `collection` in the `initialize`
function:
var base = Class.create({
itterations:0,
initialize: function() {
this.collection = [];
this.itterations++;
this.collection.push(this.itterations);
console.log('Itterations: %s, Number items in Collection: %s',
this.itterations, this.collection.size());
}
});
Now you may be thinking: But why did he move `collection` but not
`itterations`? (BTW, just the two "t"s in that, rather than
three. ;-) ) We don't assign to `itterations` either, do we? Actually
we do:
this.itterations++;
It doesn't look like an assignment, but it basically means:
this.itterations = this.itterations + 1;
...and so it creates an "own" copy of the property on the instance,
rather than incrementing the one on the prototype. (Subtle, that one,
and I had to go check to be sure.)
Happy coding,
--
T.J. Crowder
Independent Software Engineer
tj / crowder software / com
www / crowder software / com