(easy explanation)
The prototype
property only applies when using a function
as constructor (by using the new
operator). The function
creates a clone of it's prototype
and the this
keyword inside the function is set to the clone. The properties on the clone are direct references/pointers to the prototypes
properties.
The object literal {}
is a more powerfull expression alternative to new Object()
and as such "inherits" properties from Object.prototype
.
So:
function ClassLike() {}
ClassLike.prototype = {
foo : "bar"
}
var instance = new ClassLike();
alert( instance.foo ); // bar
Works because the new
operator kicks some operations in motion to create a new object whereas:
var instance = {
foo : "bar"
}
instance.prototype = {
baz : "foobar"
}
Merely adds another property (prototype) to an already created object and no process is put in motion to actually assign/change the objects original prototype.
Now Mozilla has added a non standard (IE does not support it) way to change an already instantiated objects prototype through __proto__
and there are some petitions going to add it to ES5 (EcmaScript 5). I would not use it atm. but it works like this:
var instance = {};
var parent = {
foo : "bar"
}
instance.__proto__ = parent;
alert( instance.foo ); // bar
Another way to change an already instantiated object's prototype is to add to the Object
constructors prototype (which is not advised for many reasons). As such:
var instance = {}; // a more powerful alternative to `new Object()`
Object.prototype.foo = "bar";
alert( instance.foo ); // bar
It's all possible, though wether it's wise to do it... I'd say no, but opinions vary and I rather avoid the debate ;)
Anyways, just remember that the prototype
property on works when you new
a function
, otherwise it just becomes a property on the instance.