I was recently looking at the prototype library
(http://prototype.conio.net/) and I noticed the author used the
following syntax:
Object.extend(MyObj.prototype, {
my_meth1: function(){},
my_meth2: function(){}
});
to define new methods on the MyObj prototype object. Object.extend
simply merges the two objects passed in. In this case MyObj.prototype
is our empty prototype object and the object literal is what we are
merging in. I really like this approach over the standard:
MyObj.prototype.my_meth1 = function(){};
MyObj.prototype.my_meth2 = function(){};
I like it because it allows me to use object initializers to define my
object (which is shorter, less error prone and keeps my code DRY) but
it doesn't squash any already existing properties on the object (kind
of feels like the open classes feature in Ruby). The only thing I don't
like about it is the need for using a function to do the merge. So I
got thinking of an alternate implementation that doesn't have this
problem but still has the same advantages. What if we did:
with(MyObj.prototype) {
function my_meth1(){}
function my_meth2(){}
}
It is my understanding that
function myfunc() {
}
is the exact same as
var myfunc = function(){}
which is the exact same as:
<current scope object>.myfunc = function() {}
Of course most of the time you can't access the top item on the scope
chain but that is what I understand to be happening behind the scenes.
Since the "with" statement puts my own object at the top of the scope
chain it seems that any functions defined in the with block would cause
a new property to be create on the specified object. This should allow
me to do what I want without using any special function (just builtin
stuff).
So I decided to try this experiment and it seemed to fail. I define my
object as follows:
var Car = function() {}
with(Car.prototype) {
function start() {
alert('starting');
}
}
mycar = new Car();
mycar.start();
This gives me an error about "start" not being defined on mycar. I
never get any errors with the with statement. It just seems that
functions defined in the with block don't get added to the Car
prototype object.
Anybody got any suggestions or ideas. I tested this theory under
Firefox.
Eric