(simple explanation) The prototype property applies only when using the function as constructor (using the new operator). function creates a clone of this prototype , and the keyword this inside the function is set to a clone. Properties on a clone are direct links / pointers to prototypes properties.
The literal object {} is a more powerful 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 );
It works because the new operator starts some operations in motion to create a new object, whereas:
var instance = { foo : "bar" } instance.prototype = { baz : "foobar" }
It simply adds another property (prototype) to the already created object and no process starts to actually assign / change the original prototype of the objects.
Now Mozilla has added a non-standard (IE does not support it) way of changing the prototype of already created objects via __proto__ , and there are some petitions that will add it to ES5 (EcmaScript 5). I would not use it. but it works as follows:
var instance = {}; var parent = { foo : "bar" } instance.__proto__ = parent; alert( instance.foo );
Another way to change the prototype of an already created object is to add Object to the prototype of the constructors (which is not recommended for many reasons). In this way:
var instance = {};
All this is possible, although it is reasonable to do it ... I would say no, but opinions change, and I prefer to avoid discussions;)
In any case, just remember that the prototype property works when you are new a function , otherwise it will just become an instance property.
source share