Hey all,
What are the pros and cons of defining methods in the constructor vs
through the prototype? For example:
Constructing:
-------------
function MyObj()
{
this.MyMethod = function() {};
}
Prototyping:
------------
function MyObj() {}
MyObj.prototype.MyMethod = function() {};
Currently, I'm of the mindset that the former method is preferable in
all situations except where you don't have access to the constructor
(e.g. adding to Object or Array or whatnot). Part of my reasoning is
personal preference for how the code looks, but what really got me
started coding with the former method was my switch to using closures.
I use closures to keep an object reference even in event handlers, by
beginning every object with a "var self = this;" line. The problem with
prototype functions being that they don't have the closure.
So,
-------
function MyObj()
{
var self = this;
self.msg = 'Hello World';
self.toString = function() {return self.msg};
}
alert(new MyObj);
-------
works, but
-------
function MyObj()
{
var self = this;
self.msg = 'Hello World';
}
MyObj.prototype.toString = function() {return self.msg};
alert(new MyObj);
-------
does not. From that basic advantage of defining a method in the
constructor, it's a quick appeal to consistency to arrive at the
conclusion that it's the preferred method overall.
In summary, it appears to me that defining a method in the constructor
gives you every advantage of prototyping the method, except one: you
can prototype a method in without access to the constructor code. On
the other hand, prototyping has the bigger disadvantage of not being
able to use the forementioned closure. Well, at least *I* think it's a
bigger disadvantage. Plus I like the "containedness" of defining
functions within the constructor, vs. the sprawl of prototyping.
So what am I missing?
Lance