Prototype-based programming
Prototype-based programming , also known as classless object orientation , is a form of object-oriented programming that dispenses with the language element of the class . Objects are not created by instantiating a class, but by cloning existing objects. With this cloning, all properties ( attributes and methods ) of the prototype object are copied, but they can be overwritten and the new object can be given new properties.
All existing objects can be prototypes of new objects.
Some languages completely copy the objects when they are cloned and there is no link between the clone and its prototype; however, most prototype-based languages use a special attribute that maintains a connection from the clone to the prototype. All objects cloned from the prototype also inherit subsequent changes to the prototype via this connection .
The objects can be understood as an associative array ; The key of this table are usually slot mentioned, wherein not usually between attributes (data) and methods (operations) of the object is discriminated: Methods slots often refer only to lie outside of the object code.
Advantages and disadvantages
Prototype-based languages allow greater flexibility in modeling, as they do not force the programmer to put his objects in a static class structure that is defined at compile time . Objects remain structurally changeable at runtime . However, this flexibility also includes the risk of poorer maintainability of the program.
Many optimizations that the compiler can already make in class-based languages at the time of translation cannot be implemented because of the dynamic nature of prototype-based languages.
example
The following example in ECMAScript 5 first creates an object object1
that we will then use as a prototype. It has the attributes a
and b
, to which the values 1 and 2 are assigned.
var object1 = { a : 1, b : 2 };
There is a predefined function for cloning in ECMAScript 5 Object.create()
. The desired prototype is given as an argument. This clone is named in the example object2
.
var object2 = Object.create( object1 );
Further attributes can now be assigned to this new object
object2.c = 3;
object2.d = 4;
The cloned object now has four attributes:
- a = 1 (inherited from the prototype)
- b = 2 (inherited from the prototype)
- c = 3 (added after cloning)
- d = 4 (added after cloning)
List of prototype-based programming languages
- Self
-
ECMAScript
- JavaScript
- ActionScript (increasingly class-oriented since AS3)
- Io
- Lua
- REBOL
- NewtonScript
- Snap! (BYOB) - as the only education-oriented visual programming language in this list so far
- SimTalk
In principle, any programming language that supports pointers can be programmed on the basis of prototypes. There are ready- made modules for Ruby and Perl that support this.