[Javascript] custom extension of Array object

liorean liorean at gmail.com
Thu Apr 14 19:23:38 CDT 2005


On 4/14/05, james <james at southspace.org> wrote:
> At 19:22 14/04/2005 +0200, you wrote:
> aha! what I was doing was this
> 
> function CustomArray() {
>          this.prototype = new Array();
>             .....
> }
> 
> which doesn't work!
> 
> is there a difference between setting the prototype of the object and
> setting the prototype of the constructor function??.

Yes certainly. You see, JavaScript has first class functions. First
class functions means that functions need to inherit from the Function
object, not the Object object. Constructors are just special cases of
functions that are called using the new keyword. Where does this put
the prototype property?

Let's have a look at how JavaScript inheritance works. All objects
have a prototype object. Let's call this the [[prototype]] property.
Each time you do a member lookup, it does something vaguely like this:

 1. Set the this object to the current object.
 2. Search for the property on the current object.
 3. If found, return that property.
 4. If not found, set the current object to the [[prototype]] property
 5. If current object is null, return undefined.
 6. Otherwise repeat from 2.

Each object will have it's [[prototype]] propety defined at creation
time. An engine might provide direct access to [[prototype]], like the
__proto__ propery in SpiderMonkey.

Constructors both need their own [[prototype]] to make them inherit
from Function and need to be able to define the prototype object for
their instances. So, the solution is to in this case have two separate
properties - one you inherit your function-ness from (named
[[prototype]]), one you let your instances inherit from (named
prototype). In other words, when you create a new instance, it's
[[prototype]] property will be assigned the value of the prototype
property of it's constructor.

> sorry if this is annoying newbie stuff, I am from PHP/Lingo background, I
> love this dynamic language, but it can be very confusing!

And if I didn't confuse you even more, I'd be surprised.
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the Javascript mailing list