Entry
What are prototypes?
What is prototype inheritance?
Feb 23rd, 2000 21:47
Nathan Wallace, Martin Honnen, Martin Honnen
The client side javascript docs on developer.netscape.com have a page to
page comparison on how to define classes with java compared to object
prototypes with js.
Using a prototype is just the javascript way of definining a class/type
of objects with certain properties and methods.
Say you know you need to store data of persons aggregrated from a name
and an address you may have some declarational way in some language as
follows (pseudo code)
class Person {
String name;
String address;
}
In js you would define a constructor function for such objects
function Person (name, address) {
this.name = name || '';
this.address = address || '';
}
To create a person object you then use the expression
new Person ('some name', 'some address')
To add methods to the objects of your class you define a javascript
function
function PersonToString () {
return 'Name: ' + this.name + '\nAddress: ' + this.address;
}
and instead of having some declarational way of including that function
in the class declaration you assign it as a property to the prototype
Person.prototype.toString = PersonToString;
That just means that every object created with
new Person (...)
will have a method
toString
defined.
Inheritance just means that you extend a certain class/type of object by
adding new properties and/or methods. For instance you could have a
subclass NetPerson of Person which additionally to the name and address
has a url property.
Now instead of having a declaration
class NetPerson extends Person {
String url;
}
in js you simply define a new constructor
function NetPerson (name, address, url) {
this.base = Person;
this.base(name, address);
this.url = url || '';
}
for which you need to add the info that it inherits from Person. With js
you write
NetPerson.prototype = new Person();
to do that.