Simple javascript question...

1 view
Skip to first unread message

Ngan Pham

unread,
Mar 30, 2010, 12:17:04 AM3/30/10
to closure-lib...@googlegroups.com
What's the difference between...

foo.Bar.prototype.something_ = [];

and...

foo.Bar = function() {
  this.something_ = [];
};

Steve Dee

unread,
Mar 30, 2010, 4:22:43 AM3/30/10
to closure-lib...@googlegroups.com
Data structures in the prototype are instantiated once per type; data structures in the constructor are instantiated once per instance. So Foo.prototype.something_ = [] will create one array shared by all Foo instances, whereas Foo = function() { this.something_ = []; } will create a new array for each Foo instance. E.g.:

Foo = function() { };
Foo.prototype.baz_ = [];
var x = new Foo(), y = new Foo();
x.unshift('hi');
alert(y.baz_[0]); // Says "hi".

Generally, you want to store methods in your prototypes, not data structures. The latter will cause lots of unexpected behavior. If you want type-level data structures, it's a much better idea to say Foo.baz_ = []; instead.

To unsubscribe from this group, send email to closure-library-discuss+unsubscribegooglegroups.com or reply to this email with the words "REMOVE ME" as the subject.

Ngan Pham

unread,
Mar 30, 2010, 10:29:26 AM3/30/10
to closure-lib...@googlegroups.com
Ah thank you! much appreciated!

Daniel Nadasi

unread,
Mar 30, 2010, 2:04:24 AM3/30/10
to closure-lib...@googlegroups.com
The prototype is shared between objects created from the same function. So, for example:

var b1 = new foo.Bar();
var b2 = new foo.Bar();
b1.something_.push("1");
b2.something_.push("2");
alert(b2.something_);

would alert "1,2" for the first case, but only "2" in the second. Prototypes thus are most commonly used for sharing methods between objects of the same type (to avoid duplication), and inheritance-like constructions. For example, look at goog.inherits in base.js for how basic inheritance is implemented in Closure.

- Daniel

To unsubscribe from this group, send email to closure-library-discuss+unsubscribegooglegroups.com or reply to this email with the words "REMOVE ME" as the subject.

Reply all
Reply to author
Forward
0 new messages