Prototype-based programming is a style of
object-oriented programming
Object-oriented programming (OOP) is a programming paradigm based on the concept of " objects", which can contain data and code. The data is in the form of fields (often known as attributes or ''properties''), and the code is in the form of ...
in which behaviour reuse (known as
inheritance
Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offici ...
) is performed via a process of reusing existing
objects
that serve as
prototypes. This model can also be known as ''prototypal'', ''prototype-oriented,'' ''classless'', or ''instance-based'' programming.
Prototype-based programming uses the process generalized objects, which can then be cloned and extended. Using fruit as an example, a "fruit" object would represent the properties and functionality of fruit in general. A "banana" object would be cloned from the "fruit" object and general properties specific to bananas would be appended. Each individual "banana" object would be cloned from the generic "banana" object. Compare to the
class-based paradigm, where a "fruit" ''class'' would be extended by a "banana" ''class''.
The first prototype-oriented
programming language
A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language.
The description of a programming l ...
was
Self
The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
, developed by
David Ungar
David Michael Ungar, an American computer scientist, co-created the Self programming language with Randall Smith. The SELF development environment's animated user experience was described in the paper ''Animation: From Cartoons to the User Int ...
and Randall Smith in the mid-1980s to research topics in object-oriented language design. Since the late 1990s, the classless paradigm has grown increasingly popular. Some current prototype-oriented languages are
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
(and other
ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scriptin ...
implementations such as
JScript and
Flash's
ActionScript
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meani ...
1.0),
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
,
Cecil,
NewtonScript,
Io,
Ioke,
MOO,
REBOL and
AHK.
Design and implementation
Prototypal inheritance in JavaScript is described by
Douglas Crockford as
Advocates of prototype-based programming argue that it encourages the programmer to focus on the behavior of some set of examples and only later worry about classifying these objects into archetypal objects that are later used in a fashion similar to
classes.
Many prototype-based systems encourage the alteration of prototypes during
run-time, whereas only very few class-based object-oriented systems (such as the dynamic object-oriented system,
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
,
Dylan,
Objective-C
Objective-C is a general-purpose, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was selected by NeXT for its N ...
,
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
,
Python,
Ruby
A ruby is a pinkish red to blood-red colored gemstone, a variety of the mineral corundum (aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapp ...
, or
Smalltalk
Smalltalk is an object-oriented, dynamically typed reflective programming language. It was designed and created in part for educational use, specifically for constructionist learning, at the Learning Research Group (LRG) of Xerox PARC by ...
) allow classes to be altered during the execution of a program.
Almost all prototype-based systems are based on
interpreted and
dynamically typed
In computer programming, a type system is a logical system comprising a set of rules that assigns a property called a type to every "term" (a word, phrase, or other set of symbols). Usually the terms are various constructs of a computer program ...
languages. Systems based on
statically typed languages are technically feasible, however. The Omega language discussed in ''Prototype-Based Programming'' is an example of such a system, though according to Omega's website even Omega is not exclusively static, but rather its "compiler may choose to use static binding where this is possible and may improve the efficiency of a program."
Object construction
In prototype-based languages there are no explicit classes. Objects inherit directly from other objects through a prototype property. The prototype property is called
prototype
in
Self
The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
and
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
, or
proto
in
Io. There are two methods of constructing new objects: ''
ex nihilo'' ("from nothing") object creation or through ''cloning'' an existing object. The former is supported through some form of object
literal
Literal may refer to:
* Interpretation of legal concepts:
** Strict constructionism
** The plain meaning rule (a.k.a. "literal rule")
* Literal (mathematical logic), certain logical roles taken by propositions
* Literal (computer programmin ...
, declarations where objects can be defined at runtime through special syntax such as
and passed directly to a variable. While most systems support a variety of cloning, ''ex nihilo'' object creation is not as prominent.
In class-based languages, a new instance is constructed through a class's
constructor function
In class-based, object-oriented programming, a constructor (abbreviation: ctor) is a special type of subroutine called to create an object. It prepares the new object for use, often accepting arguments that the constructor uses to set required ...
, a special function that reserves a block of memory for the object's members (properties and methods) and returns a reference to that block. An optional set of constructor
arguments
An argument is a statement or group of statements called premises intended to determine the degree of truth or acceptability of another statement called conclusion. Arguments can be studied from three main perspectives: the logical, the dialectic ...
can be passed to the function and are usually held in properties. The resulting instance will inherit all the methods and properties that were defined in the class, which acts as a kind of template from which similarly typed objects can be constructed.
Systems that support ''ex nihilo'' object creation allow new objects to be created from scratch without cloning from an existing prototype. Such systems provide a special syntax for specifying the properties and behaviors of new objects without referencing existing objects. In many prototype languages there exists a root object, often called ''Object'', which is set as the default prototype for all other objects created in run-time and which carries commonly needed methods such as a
toString()
function to return a description of the object as a string. One useful aspect of ''ex nihilo'' object creation is to ensure that a new object's slot (properties and methods) names do not have
namespace
In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified.
Namespaces ...
conflicts with the top-level ''Object'' object. (In the
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
language, one can do this by using a null prototype, i.e.
Object.create(null)
.)
''Cloning'' refers to a process whereby a new object is constructed by copying the behavior of an existing object (its prototype). The new object then carries all the qualities of the original. From this point on, the new object can be modified. In some systems the resulting child object maintains an explicit link (via ''
delegation
Delegation is the assignment of authority to another person (normally from a manager to a subordinate) to carry out specific activities. It is the process of distributing and entrusting work to another person,Schermerhorn, J., Davidson, P., Poole ...
'' or ''
resemblance
Resemblance may refer to:
*Similarity (philosophy)
*Resemblance nominalism
*Family Resemblance (anthropology)
*Ludwig Wittgenstein's family resemblances
*In text mining, the degree to which two documents resemble each other, calculated using shingl ...
'') to its prototype, and changes in the prototype cause corresponding changes to be apparent in its clone. Other systems, such as the
Forth
Forth or FORTH may refer to:
Arts and entertainment
* ''forth'' magazine, an Internet magazine
* ''Forth'' (album), by The Verve, 2008
* ''Forth'', a 2011 album by Proto-Kaw
* Radio Forth, a group of independent local radio stations in Scotla ...
-like programming language
Kevo, do not propagate change from the prototype in this fashion and instead follow a more ''concatenative'' model where changes in cloned objects do not automatically propagate across descendants.
// Example of true prototypal inheritance style
// in JavaScript.
// object creation using the literal
// object notation .
const foo = ;
// Another object.
const bar = ;
// Object.setPrototypeOf() is a method introduced in ECMAScript 2015.
// For the sake of simplicity, let us pretend
// that the following line works regardless of the
// engine used:
Object.setPrototypeOf(bar, foo); // foo is now the prototype of bar.
// If we try to access foo's properties from bar
// from now on, we'll succeed.
bar.one; // Resolves to 1.
// The child object's properties are also accessible.
bar.three; // Resolves to 3.
// Own properties shadow prototype properties
bar.two; // Resolves to "two"
bar.name; // unaffected, resolves to "foo"
foo.name; // Resolves to "foo"
For another example:
const foo = ;
// bar. prototype = foo
const bar = Object.create(foo);
bar.three = 3;
bar.one; // 1
bar.two; // 2
bar.three; // 3
Delegation
In prototype-based languages that use ''delegation'', the language runtime is capable of
dispatching the correct method or finding the right piece of data simply by following a series of delegation pointers (from object to its prototype) until a match is found. All that is required to establish this behavior-sharing between objects is the delegation pointer. Unlike the relationship between class and instance in class-based object-oriented languages, the relationship between the prototype and its offshoots does not require that the child object have a memory or structural similarity to the prototype beyond this link. As such, the child object can continue to be modified and amended over time without rearranging the structure of its associated prototype as in class-based systems. It is also important to note that not only data, but also methods can be added or changed. For this reason, some prototype-based languages refer to both data and methods as "slots" or "members".
Concatenation
In ''concatenative'' prototyping - the approach implemented by the Kevo programming language - there are no visible pointers or links to the original prototype from which an object is cloned. The prototype (parent) object is copied rather than linked to and there is no delegation. As a result, changes to the prototype will not be reflected in cloned objects.
The main conceptual difference under this arrangement is that changes made to a prototype object are not automatically propagated to clones. This may be seen as an advantage or disadvantage. (However, Kevo does provide additional primitives for publishing changes across sets of objects based on their similarity — so-called ''family resemblances'' or ''clone family'' mechanism
— rather than through taxonomic origin, as is typical in the delegation model.) It is also sometimes claimed that delegation-based prototyping has an additional disadvantage in that changes to a child object may affect the later operation of the parent. However, this problem is not inherent to the delegation-based model and does not exist in delegation-based languages such as JavaScript, which ensure that changes to a child object are always recorded in the child object itself and never in parents (i.e. the child's value shadows the parent's value rather than changing the parent's value).
In simplistic implementations, concatenative prototyping will have faster member lookup than delegation-based prototyping (because there is no need to follow the chain of parent objects), but will conversely use more memory (because all slots are copied, rather than there being a single slot pointing to the parent object). More sophisticated implementations can avoid this problem, however, although trade-offs between speed and memory are required. For example, systems with concatenative prototyping can use a
copy-on-write
Copy-on-write (COW), sometimes referred to as implicit sharing or shadowing, is a resource-management technique used in computer programming to efficiently implement a "duplicate" or "copy" operation on modifiable resources. If a resource is dupl ...
implementation to allow for behind-the-scenes data sharing — and such an approach is indeed followed by Kevo. Conversely, systems with delegation-based prototyping can use
caching
In computing, a cache ( ) is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewher ...
to speed up data lookup.
Criticism
Advocates of class-based object models who criticize prototype-based systems often have concerns similar to the concerns that proponents of static type systems for programming languages have of dynamic type systems (see
datatype
In computer science and computer programming, a data type (or simply type) is a set of possible values and a set of allowed operations on it. A data type tells the compiler or interpreter how the programmer intends to use the data. Most progra ...
). Usually, such concerns involve
correctness,
safety
Safety is the state of being "safe", the condition of being protected from harm or other danger. Safety can also refer to the control of recognized hazards in order to achieve an acceptable level of risk.
Meanings
There are two slightly di ...
,
predictability
Predictability is the degree to which a correct prediction or forecast of a system's state can be made, either qualitatively or quantitatively.
Predictability and causality
Causal determinism has a strong relationship with predictability. Pe ...
,
efficiency and programmer unfamiliarity.
On the first three points, classes are often seen as analogous to types (in most statically typed object-oriented languages they serve that role) and are proposed to provide contractual guarantees to their instances, and to users of their instances, that they will behave in some given fashion.
Regarding efficiency, declaring classes simplifies many
compiler
In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
optimizations that allow developing efficient method and instance-variable lookup. For the
Self
The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
language, much development time was spent on developing, compiling, and interpreting techniques to improve the performance of prototype-based systems versus class-based systems.
A common criticism made against prototype-based languages is that the community of
software developer
Software development is the process of conceiving, specifying, designing, programming, documenting, testing, and bug fixing involved in creating and maintaining applications, frameworks, or other software components. Software development inv ...
s is unfamiliar with them, despite the popularity and market permeation of
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
. This knowledge level of prototype-based systems seems to be increasing with the proliferation of
JavaScript frameworks and the complex use of JavaScript as the
Web matures. ECMAScript 6 introduced classes as
syntactic sugar over JavaScript's existing prototype-based inheritance, providing an alternative way to create objects and deal with inheritance.
Languages supporting prototype-based programming
*
Actor-Based Concurrent Language (ABCL):
ABCL/1,
ABCL/R,
ABCL/R2,
ABCL/c+
*
Agora
The agora (; grc, ἀγορά, romanized: ', meaning "market" in Modern Greek) was a central public space in ancient Greek city-states. It is the best representation of a city-state's response to accommodate the social and political order ...
*
AutoHotkey
*
Cecil and
Diesel of
Craig Chambers
*
ColdC
*
COLA
Cola is a carbonated soft drink flavored with vanilla, cinnamon, citrus oils and other flavorings. Cola became popular worldwide after the American pharmacist John Stith Pemberton invented Coca-Cola, a trademarked brand, in 1886, which was ...
*
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in ANSI standard document ''ANSI INCITS 226-1994 (S20018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperlinked HTML version, has been derived fr ...
Cyan*
ECMAScript
ECMAScript (; ES) is a JavaScript standard intended to ensure the interoperability of web pages across different browsers. It is standardized by Ecma International in the documenECMA-262
ECMAScript is commonly used for client-side scriptin ...
**
ActionScript
ActionScript is an object-oriented programming language originally developed by Macromedia Inc. (later acquired by Adobe). It is influenced by HyperTalk, the scripting language for HyperCard. It is now an implementation of ECMAScript (meani ...
1.0, used by
Adobe Flash
Adobe Flash (formerly Macromedia Flash and FutureSplash) is a multimedia software platform used for production of animations, rich web applications, desktop applications, mobile apps, mobile games, and embedded web browser video players. Fla ...
and
Adobe Flex
**
E4X
**
JavaScript
JavaScript (), often abbreviated as JS, is a programming language that is one of the core technologies of the World Wide Web, alongside HTML and CSS. As of 2022, 98% of Website, websites use JavaScript on the Client (computing), client side ...
**
JScript
**
TypeScript
*
Io
*
Ioke
*
Jsonnet
*
Logtalk
*
LPC
LPC may refer to:
Science and technology
* Linear predictive coding, a method used in audio signal processing and speech processing
* Leaf protein concentrate, a concentrated form of the proteins found in the leaves of plants
* Long period comet, ...
*
Lua
Lua or LUA may refer to:
Science and technology
* Lua (programming language)
* Latvia University of Agriculture
* Last universal ancestor, in evolution
Ethnicity and language
* Lua people, of Laos
* Lawa people, of Thailand sometimes referred t ...
*
M2000
*
Maple
''Acer'' () is a genus of trees and shrubs commonly known as maples. The genus is placed in the family Sapindaceae.Stevens, P. F. (2001 onwards). Angiosperm Phylogeny Website. Version 9, June 2008 nd more or less continuously updated since ht ...
*
MOO
*
Neko
*
NewtonScript
*
Nim
Nim is a mathematical two player game.
Nim or NIM may also refer to:
* Nim (programming language)
* Nim Chimpsky, a signing chimpanzee Acronyms
* Network Installation Manager, an IBM framework
* Nuclear Instrumentation Module
* Negative index met ...
*
Nix
Nix or NIX may refer to:
Places
* Nix, Alabama, an unincorporated community, United States
* Nix, Texas, a ghost town in southwestern Lampasas County, Texas, United States
* Nix (moon), a moon of Pluto
People
* Nix (surname), listing people ...
*
Object Lisp
*
Obliq
*
Omega
Omega (; capital: Ω, lowercase: ω; Ancient Greek ὦ, later ὦ μέγα, Modern Greek ωμέγα) is the twenty-fourth and final letter in the Greek alphabet. In the Greek numeric system/ isopsephy ( gematria), it has a value of 800. Th ...
*
OpenLaszlo
*
Perl
Perl is a family of two High-level programming language, high-level, General-purpose programming language, general-purpose, Interpreter (computing), interpreted, dynamic programming languages. "Perl" refers to Perl 5, but from 2000 to 2019 it ...
, with the Class::Prototyped module
*
Python wit
prototype.py
*
R, with the proto package
*
REBOL
*
Red (programming language)
*
Ruby (programming language)
Ruby is an interpreted, high-level, general-purpose programming language which supports multiple programming paradigms. It was designed with an emphasis on programming productivity and simplicity. In Ruby, everything is an object, including ...
*
Self
The self is an individual as the object of that individual’s own reflective consciousness. Since the ''self'' is a reference by a subject to the same subject, this reference is necessarily subjective. The sense of having a self—or ''selfhood ...
*
Seph
*
Slate (programming language)
Slate is a fine-grained, foliation (geology), foliated, homogeneous metamorphic rock derived from an original shale-type sedimentary rock composed of clay or volcano, volcanic ash (volcanic), ash through low-grade regional metamorphism. It is t ...
*
SmartFrog
SmartFrog (''Smart Framework for Object Groups'') is a Java based open-source framework for helping host large-scale applications across component-based distributed system. It is proposed to make the design, configuration, deployment and management ...
*
Snap!
*
Etoys
*
TADS
*
Tcl with snit extension
*
Umajin[Proprietary scripting language. http://www.davidbrebner.com/?p=4 has some basic examples of use.]
See also
*
Class-based programming (contrast)
*
Differential inheritance
*
Programming paradigm
Programming paradigms are a way to classify programming languages based on their features. Languages can be classified into multiple paradigms.
Some paradigms are concerned mainly with implications for the execution model of the language, s ...
References
Further reading
*
Class Warfare: Classes vs. Prototypes by Brian Foote.
*
by Henry Lieberman, 1986.
{{DEFAULTSORT:Prototype-Based Programming
Object-oriented programming
Programming paradigms
Type theory