On Dec 22, 2:18 am, blackholebutter...@gmail.com wrote:
Why isn't this allowed?
function Foo(){
this.param1 = 'Constructor Function Foo';
}
var foo = new Foo;
var newfoo = new foo;
The last line above gives an error. I thought all objects could be
used as constructors. But it seems the foo object above cannot be used
with the 'new' operator to create more objects. Does anyone know why
that is?
Thanks.
Javascript's object inheritence model is prototypal. But for a bunch
of historical reasons the designers of the language decided to
implement a model which tries to emulate classical inheritence (hence
the new keyword). This is why as you've found out "new" works for
"Constructor" objects but not for regular objects.
Other prototypal languages have an "object" operator instead of "new".
Traditionally, the difference between "object" and "new" is that while
"new" creates an object instance from a class (or constructor
functions in javascript) "object" creates an object instance directly
from a live object. Unfortunately the designers of javascript, while
trying to bend it to emulate classical inheritence, neglected to
provide an object operator/function.
Fortunately javascript's prototype model is complete enough that we
can write our own object method:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
So now you can write:
function Foo(){
this.param1 = 'Constructor Function Foo';
}
var foo = new Foo;
var newfoo = object(foo);
See
http://javascript.crockford.com for more on this topic.