Prototypal inheritance in JavaScript

Lucian Branescu lucian.branescu at gmail.com
Tue Jun 14 12:21:11 UTC 2011


On 14 June 2011 12:51, rohit jangid <rohit.nsit08 at gmail.com> wrote:
> Hi,
> I ran into a confusion in prototypal inheritance in javascript,
>
> in this code
>
> var Constructor = function(){};
> Constructor.prototype.hello = "hello"
> Constructor.prototype.value = 1;
> Constructor.prototype.test = function() { console.log(this.hello); };
>
> // creating object from this constructor class
>
> var rj = new Constructor();    // create an instance of A
>
> rj.test();
>
> console.log(rj);
> console.log(rj.prototype);
>
> **********************************output*************************************************************
> hello
> {}
> undefined
>
>
> how object is knowing that it can use test() function as it is not its
> own property and neither in its prototype

Afaict, 'test' is a property of its prototype. You can either set
obj.prototype to some object, or set obj.prototype.attr to some value,
and afaik obj.prototype gets created automatically, as a plain Object.

> even logically the properties shouldn't be copied into the new object
> as int that case it will be static, while we know any further
> additions to Constructor.prototype will be reflected immediately in
> the object .

Properties of the prototype aren't copied into the object. When an
attribute is looked up, it is first looked up in the object; if that
fails, it is looked up in the prototype, and the prototype's
prototype, and so on up the inheritance chain.

> Is there any hidden refrence created to the Constructor.prototype in
> object . Or I'm missing some general point here?

JS inheritance can be confusing. I may be wrong, but I think rj's
prototype is in fact the Constructor object.


More information about the parrot-dev mailing list