Jump to content

Prototype-based programming: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
Dougher (talk | contribs)
Line 70: Line 70:


==Delegation==
==Delegation==
In prototype-based languages that use ''delegation'', the language runtime is capable of [[dynamic dispatch|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, most prototype-based languages refer to both data and methods as "slots".{{Citation needed|reason=Sentence needs at least 1 citation. I've coded professionally in JS(all variants) & ActionScript for 4 years, and I've NEVER seen "slots" used this way in JS, and rarely in AS. E.g. see inconsistent/nonexistent usage in following: [http://www.google.com/#q=javascript+methods+properties+slots&hl=en&pws=0&biw=1247&bih=673&site=webhp&fp=528dfc887ad8eb4a&bav=on.2,or.r_gc.r_pw.,cf.osb&cad=b] & [http://www.google.com/#q=actionscript+methods+properties+slots&hl=en&pws=0&biw=1247&bih=673&site=webhp&fp=1&bav=on.2,or.r_gc.r_pw.,cf.osb&cad=b] . I'm calling 'Citation-needing', if not 'Dubious'.|January 2012|date=January 2012}}
In prototype-based languages that use ''delegation'', the language runtime is capable of [[dynamic dispatch|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".{{Citation needed|reason=Sentence needs at least 1 citation. I've coded professionally in JS(all variants) & ActionScript for 4 years, and I've NEVER seen "slots" used this way in JS, and rarely in AS. E.g. see inconsistent/nonexistent usage in following: [http://www.google.com/#q=javascript+methods+properties+slots&hl=en&pws=0&biw=1247&bih=673&site=webhp&fp=528dfc887ad8eb4a&bav=on.2,or.r_gc.r_pw.,cf.osb&cad=b] & [http://www.google.com/#q=actionscript+methods+properties+slots&hl=en&pws=0&biw=1247&bih=673&site=webhp&fp=1&bav=on.2,or.r_gc.r_pw.,cf.osb&cad=b] . I'm calling 'Citation-needing', if not 'Dubious'.|January 2012|date=January 2012}}


==Concatenation==
==Concatenation==

Revision as of 01:41, 21 December 2012

Prototype-based programming is a style of object-oriented programming in which classes are not present, and behavior reuse (known as inheritance in class-based languages) is performed via a process of cloning existing objects that serve as prototypes. This model can also be known as classless, prototype-oriented or instance-based programming. Delegation is the language feature that supports prototype-based programming.

The first prototype-oriented programming language was Self developed by David Ungar 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 ECMAScript (and its implementations JavaScript, JScript and Flash's ActionScript), Cecil, NewtonScript, Io, MOO, REBOL, and Lisaac.

Comparison with class-based models

With class-based languages, the structure of objects is specified in programmer-defined types called classes. While classes define the type of data and functionality that objects will have, instances are "usable" objects based on the patterns of a particular class. In this model, classes act as collections of behavior (methods) and structure that are the same for all instances, whereas instances carry the objects' data. The role distinction is thus primarily based on a distinction between structure and behavior on the one hand, and state on the other.

Advocates of prototype-based programming often argue that class-based languages encourage a model of development that focuses first on the taxonomy and relationships between classes. In contrast, prototype-based programming is seen as encouraging 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.[1] As such, 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, Dylan, Smalltalk, Objective-C, Python, Perl, or Ruby) allow classes to be altered during the execution of a program.

Almost all prototype-based systems are based on interpreted and dynamically typed languages. Systems based on statically typed languages are technically feasible, however. The Omega language discussed in Prototype-Based Programming[2] 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."

See section "Criticism" for further comparison.

Object construction

In class-based languages, a new instance is constructed through the class' constructor function, 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 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 similar typed objects can be constructed.

In prototype-based languages there are no explicit classes and objects inherit directly from other objects with whom they are linked through a property, often called prototype as in the case of Javascript. 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, 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.[3]

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 names do not have namespace conflicts with the top-level Object object. (In the Mozilla JavaScript implementation, one can do this by setting a newly constructed object's __proto__ property to 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 or resemblance) to its prototype, and changes in the prototype cause corresponding changes to be apparent in its clone. Other systems, such as the Forth-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.[1]

// Example of true prototypal inheritance style 
// in JavaScript.

// "ex nihilo" object creation using the literal 
// object notation {}.
var foo = {name: "foo", one: 1, two: 2};

// Another "ex nihilo" object.
var bar = {three: 3};

// Gecko and Webkit JavaScript engines can directly 
// manipulate the internal prototype link.
// For the sake of simplicity, let us pretend 
// that the following line works regardless of the 
// engine used:
bar.__proto__ = 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.name = "bar";
foo.name; // unaffected, resolves to "foo"
bar.name; // Resolves to "bar"

This example in JS 1.8.5 + ( see http://kangax.github.com/es5-compat-table/ )

var foo = {one: 1, two: 2};

// bar.[[ prototype ]] = foo
var 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".[citation needed]

Concatenation

Under pure prototyping, which is also referred to as concatenative prototypes, and is exemplified in the Kevo language, there are no visible pointers or links to the original prototype from which an object is cloned. The prototype object is copied exactly, but given a different name (or reference). Behavior and attributes are simply duplicated as-is.

One advantage of this approach is that object authors can alter the copy without worrying about side-effects across other children of the parent. Another advantage is that method lookup during dispatch is much cheaper computationally than with delegation, where an exhaustive search must be made of the entire delegation chain before failure to find a method or slot can be admitted.

Disadvantages to the concatenative approach include the organizational difficulty of propagating changes through the system; if a change occurs in a prototype, it is not immediately or automatically available on its clones. However, Kevo does provide additional primitives for publishing changes across sets of objects based on their similarity (so-called family resemblances) rather than through taxonomic origin, as is typical in the delegation model.

Another disadvantage is that, in the most naive implementations of this model, additional memory is wasted (versus the delegation model) on each clone for the parts that have stayed the same between prototype and clone. However, it is possible to provide concatenative behavior to the programming while sharing implementation and data behind-the-scenes; such an approach is indeed followed by Kevo.[4]

An alternative quasi-solution to the problem of clones interfering with the behavior of the parent is to provide a means whereby the potential parent is flagged as being clonable or not. In MOO, this is achieved with the "f" ("fertile") flag. Only objects with the "f" flag can be cloned. In practice, this leads to certain objects serving as surrogate classes; their properties are kept constant to serve as initial values for their children. These children then tend to have the "f" flag not set.

Criticism

Advocates of class-based object models who criticize prototype-based systems often have concerns that could be seen as similar to those concerns that proponents of static type systems for programming languages have of dynamic type systems (see datatype). Usually, such concerns involve: correctness, safety, predictability, 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 optimizations that allow developing efficient method and instance variable lookup. For the Self language, much development time was spent on developing, compiling, and interpreting techniques to improve the performance of prototype-based systems versus class-based systems. For example, the Lisaac compiler produces code almost as fast as C. Tests have been run with an MPEG-2 codec written in Lisaac, copied from a C version. These show the Lisaac version is 1.9% slower than the C version with 37% fewer lines of code.[5]

A common criticism made against prototype-based languages is that the community of software developers is unfamiliar with them, despite the popularity and market permeation of JavaScript. This knowledge level of prototype-based systems seems to be changing with the proliferation of JavaScript frameworks and increases in the complex use of JavaScript as "Web 2.0" matures.

Languages

References

  1. ^ a b Taivalsaari, Antero. "Section 1.1". Classes vs. Prototypes: Some Philosophical and Historical Observations. p. 14. CiteSeerx10.1.1.56.4713.
  2. ^ Blaschek, Günther. "Section 2.8". Omega: Statically Typed Prototypes. p. 177.
  3. ^ Dony, Chistophe; Malenfan, Jacques; Bardou, Daniel. "Section 1.2". Classifying Prototype-based Programming Languages. p. 17. {{cite book}}: External link in |chapterurl= (help); Unknown parameter |chapterurl= ignored (|chapter-url= suggested) (help)
  4. ^ Taivalsaari, Antero (1992). "Kevo, a prototype-based object-oriented programming language based on concatenation and module operations". Technical Report Report LACIR 92-02. University of Victoria.
  5. ^ "Isaac project benchmarks". Retrieved 2007-07-24.

Further reading

See also