Programming Search⌘K

Conceptcore

Prototype-based programming

Also called prototypes, prototype chain, prototypal inheritance, delegation, classless objects, object-based programming.

In prototype-based programming, objects come from other objects: a new object copies a prototype or delegates to it, and a property lookup follows the chain of parents.

Applies to
core-languages

Idea

In prototype-based programming, objects come from other objects, not from classes. A program makes a new object by copying an existing one, the prototype, or by creating an object that delegates to it: when the new object has no property of a given name, the lookup continues in its parent. Behavior shared by many objects lives in one object that they all delegate to, so a change to that object reaches all of them at once. Self introduced the model in the 1980s, and JavaScript, Lua and Io use it.

class Obj:
    """An object with its own slots and one parent to delegate to."""

    def __init__(self, parent=None, **slots):
        self.parent, self.slots = parent, dict(slots)

    def get(self, name):
        o = self
        while o is not None:  # walk the chain until a slot matches
            if name in o.slots:
                return o.slots[name]
            o = o.parent
        raise AttributeError(name)

    def set(self, name, value):  # always writes an own slot
        self.slots[name] = value

    def send(self, name, *args):
        return self.get(name)(self, *args)  # the method runs with the receiver as self

    def clone(self):
        return Obj(self.parent, **self.slots)


point_traits = Obj(  # behavior shared by all points
    describe=lambda self: f"({self.get('x')}, {self.get('y')})",
    moved=lambda self, dx, dy: Obj(self, x=self.get("x") + dx, y=self.get("y") + dy),
)
origin = Obj(point_traits, x=0, y=0)  # the prototype point

p = origin.clone()  # a new point is a copy of the prototype
p.set("x", 3)
q = p.send("moved", 1, 1)  # q delegates to p
print(origin.send("describe"), p.send("describe"), q.send("describe"))

point_traits.set("describe", lambda self: f"<{self.get('x')} {self.get('y')}>")
print(origin.send("describe"), q.send("describe"))  # one change, every point sees it

q.set("describe", lambda self: "special")  # an own slot shadows the parent's
print(q.send("describe"), p.send("describe"))
Output
(0, 0) (3, 0) (4, 1)
<0 0> <4 1>
special <3 0>

The class Obj is the whole object model. An object is a dictionary of slots and a parent. A read walks from the object to its parent and on up the chain, a write always goes to the object itself, and a method is a slot that holds a function, called with the receiver as self. point_traits holds the methods of all points, origin is a concrete point to copy, and changing describe in point_traits changes it for every point. The last line gives one object its own describe, which hides the shared one for that object only.

How it works

Objects without classes. A class-based language has two kinds of entity: classes, which describe the structure and behavior of objects, and instances, which hold the data. A prototype-based language has only objects. David Ungar and Randall Smith, the designers of Self, put the difference this way: "In a class-based language, an object would be created by instantiating a plan in its class. In a prototype-based language like SELF, an object would be created by cloning (copying) a prototype. In SELF, any object can be cloned."1 An object can also be made from nothing, as a literal with its own properties.

Delegation. Each object can have a link to a parent object, and the lookup of a property follows these links. MDN describes the chain in JavaScript: "Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype."2 A read looks first in the object, then in its prototype, and so on, "until either a property with a matching name is found or the end of the prototype chain is reached."2 Self uses the same rule: "If an object receives a message and it has no matching slot, the search continues via a parent pointer. This is how SELF implements inheritance."1 A method found in a parent runs with the original receiver as self or this, so shared code works on the data of each object.

Shadowing and writes. A write creates or changes a property of the object itself, never of its parent. An own property with the same name as one in the chain hides the parent's property for that object, which is how an object overrides shared behavior. Because reads go through the chain and writes do not, a mutable value that lives in the parent, such as an array, is shared by every object that reads it. The wrong blocks in the Python and JavaScript files show this.

Traits objects and concrete prototypes. Programs in Self and JavaScript divide the work between two kinds of object. A traits object, the prototype property of a JavaScript constructor, holds the methods that all objects of a kind share. A concrete prototype holds default data and is the object to copy or to delegate to. Ungar and Smith claimed that "Prototypes combine inheritance and instantiation to provide a framework that is simpler and more flexible than most object-oriented languages."1

Change at run time. A parent link is an ordinary reference, so a program can add a method to a shared object, replace it, or give one object a different parent while the program runs. JavaScript exposes the link through Object.create, which "creates a new object, using an existing object as the prototype of the newly created object", and through Object.getPrototypeOf and Object.setPrototypeOf.3 This flexibility is what makes a prototype language easy to extend and hard to optimize.

Classes on top of prototypes. A class-like layer is a short step from prototypes: a constructor function makes objects that delegate to one traits object. JavaScript's class syntax does exactly this, and MDN notes that "classes do not bring a new inheritance pattern."2 The reverse also holds: Python and Smalltalk find methods by searching an object, then its class, then the superclasses, which is delegation along a chain that the language builds from classes.

In languages

LanguageVerdictNote
PythonIdiom
C++Absent
JavaAbsent
CAbsent
C#Absent
JavaScriptNative
TypeScriptNativeAs JavaScript, with Object.create and the prototype chain; the type checker models classes and object types, not changes to a prototype at run time.
GoAbsent
RustAbsent
KotlinAbsentClasses fix the members of objects, and class delegation with by forwards an interface to another object at compile time; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyRows have no methods and no delegation to other rows.
BashDoes not applyBash has no objects.
PowerShellIdiomAdd-Member and PSCustomObject add properties and script methods to a single object at run time, without a parent link; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no objects; the DOM that scripts see is built on JavaScript prototypes.
CSSDoes not applyCSS has no objects; inherited properties are a different idea.
Regular expressionsDoes not applyA pattern has no objects.
Language Verdict Mechanism
Python idiom attribute lookup through instance, class and bases; classes change at run time
JavaScript native prototype chain; Object.create; classes built on prototypes
TypeScript native as JavaScript
Java absent maps of slots by hand; the prototype pattern with copies
Kotlin absent classes; class delegation with by
C# absent dictionaries of slots by hand; ExpandoObject
Go absent maps of slots by hand; struct embedding
Rust absent Rc parents and RefCell slots by hand
C absent structs with a parent pointer and a slot table
C++ absent maps of slots and a shared_ptr parent
Bash n/a no objects
PowerShell idiom Add-Member on single objects
SQL n/a no objects
Regex n/a no objects
HTML n/a no objects
CSS n/a no objects

JavaScript and TypeScript are the only core languages of this site with prototypes in the language. Every other language with objects is class-based, and the example files build a small prototype system by hand: a table of slots, a parent reference and a lookup that walks the chain. The files show how much each language must work around its static types: Java, C#, Go, Rust and C++ store methods as function values and cast or match on every read.

Python stands between the two models. It has classes, but a class is an object that can change at run time, and attribute lookup searches the instance, then the class and its bases, much as a prototype language searches the chain. Outside the core set, Lua builds objects from tables with a metatable whose __index field names the table to search next, and Self, Io and NewtonScript are prototype languages from the ground up.

PythonGitHub
import types


class Point:  # the class object is the parent that instances delegate to
    x = 0
    y = 0

    def describe(self):
        return f"({self.x}, {self.y})"


p = Point()
p.x = 3  # an own attribute in p.__dict__ shadows Point.x
print(p.describe(), p.__dict__, Point().describe())

Point.describe = lambda self: f"<{self.x} {self.y}>"  # change the parent at run time
print(p.describe())

p.describe = types.MethodType(lambda self: "special", p)  # a method of one object
print(p.describe(), Point().describe())


class Labeled:
    def describe(self):
        return f"label {self.x}"


p.__class__ = Labeled  # switch the parent of one object
del p.describe
print(p.describe())
Output
(3, 0) {'x': 3} (0, 0)
<3 0>
special <0 0>
label 3

This code runs but gives a wrong answer on purpose.

import copy

prototype = {"name": "form", "fields": ["id"]}

login = copy.copy(prototype)  # clone the prototype
login["name"] = "login"
login["fields"].append("password")

print(login)
print(prototype)
Output
{'name': 'login', 'fields': ['id', 'password']}
{'name': 'form', 'fields': ['id', 'password']}
  • Verdict: idiom. Python is class-based, but its attribute lookup works like delegation: a read looks in the instance dictionary, then in the class, then in the base classes, and a write goes to the instance. Classes are objects that a program can change at run time, so a new method on a class reaches every instance at once, a single object can get its own method, and assigning __class__ changes the object that an instance delegates to. A prototype system with clones and parent links, as the Idea section builds, takes a few lines.
  • The wrong block clones a prototype with copy.copy, which copies the dictionary but not the list inside it. The clone and the prototype share fields, so adding a field to login also changes the prototype and every later clone. Use copy.deepcopy, or build the mutable parts afresh in each clone.
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <variant>

// An object: own slots and a shared pointer to a parent.
struct Obj {
    using Method = std::function<std::string(const Obj&)>;
    using Slot = std::variant<int, Method>;

    std::shared_ptr<const Obj> parent;
    std::map<std::string, Slot> slots;

    const Slot& get(const std::string& name) const
    {
        for (const Obj* o = this; o != nullptr; o = o->parent.get()) {
            if (auto it = o->slots.find(name); it != o->slots.end())
                return it->second;
        }
        throw std::out_of_range("no slot " + name);
    }

    int num(const std::string& name) const { return std::get<int>(get(name)); }
    std::string send(const std::string& name) const { return std::get<Method>(get(name))(*this); }
};

int main()
{
    auto traits = std::make_shared<Obj>();
    traits->slots["describe"] = Obj::Method([](const Obj& o) {
        return "(" + std::to_string(o.num("x")) + ", " + std::to_string(o.num("y")) + ")";
    });
    auto origin = std::make_shared<Obj>(Obj{traits, {{"x", 0}, {"y", 0}}});
    Obj p{origin, {{"x", 3}}};  // p delegates to origin

    std::cout << origin->send("describe") << ' ' << p.send("describe") << '\n';
    traits->slots["describe"] = Obj::Method([](const Obj& o) {
        return "<" + std::to_string(o.num("x")) + " " + std::to_string(o.num("y")) + ">";
    });
    std::cout << origin->send("describe") << ' ' << p.send("describe") << '\n';

    Obj copy = p;  // cloning copies the own slots and shares the parent
    copy.slots["x"] = 9;
    std::cout << copy.send("describe") << ' ' << p.send("describe") << '\n';
}
Output
(0, 0) (3, 0)
<0 0> <3 0>
<9 0> <3 0>
  • Verdict: absent. C++ classes fix the members of their objects at compile time. A prototype object holds a map of slots, with std::variant for the kinds of value and std::function for methods, and a std::shared_ptr to its parent. Copying the struct copies the own slots and shares the parent, which is the clone operation of a prototype language: the copy changes its own x, and both objects still use the one describe of the shared traits object.
JavaGitHub
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

// A prototype object: own slots plus a parent to delegate to.
final class Proto {
    final Proto parent;
    final Map<String, Object> slots = new HashMap<>();

    Proto(Proto parent) { this.parent = parent; }

    Object get(String name) {
        for (Proto o = this; o != null; o = o.parent) {
            if (o.slots.containsKey(name)) return o.slots.get(name);
        }
        throw new IllegalArgumentException("no slot " + name);
    }

    Proto set(String name, Object value) { slots.put(name, value); return this; }

    @SuppressWarnings("unchecked")
    Object send(String name) { return ((Function<Proto, Object>) get(name)).apply(this); }

    Proto cloneProto() {
        Proto c = new Proto(parent);
        c.slots.putAll(slots);
        return c;
    }
}

public class Main {
    public static void main(String[] args) {
        Proto traits = new Proto(null);
        traits.set("describe", (Function<Proto, Object>) o -> "(" + o.get("x") + ", " + o.get("y") + ")");
        Proto origin = new Proto(traits).set("x", 0).set("y", 0);

        Proto p = origin.cloneProto().set("x", 3);
        System.out.println(origin.send("describe") + " " + p.send("describe"));

        traits.set("describe", (Function<Proto, Object>) o -> "<" + o.get("x") + " " + o.get("y") + ">");
        System.out.println(origin.send("describe") + " " + p.send("describe"));
    }
}
Output
(0, 0) (3, 0)
<0 0> <3 0>

This code raises CloneNotSupportedException, on purpose.

// The prototype pattern with Object.clone, on a class that forgot Cloneable.
class Shape {
    int x, y;

    Shape copy() throws CloneNotSupportedException {
        return (Shape) super.clone();  // Object.clone checks for Cloneable at run time
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Shape prototype = new Shape();
        prototype.x = 1;
        Shape s = prototype.copy();
        System.out.println(s.x);
    }
}
  • Verdict: absent. Java objects get their fields and methods from their class, and the set of fields is fixed at compile time. A program that needs objects that delegate to other objects builds them from a map of slots and a parent reference, as the run block does, with functions as methods and casts on every read. The prototype design pattern, which makes new objects by copying a configured one, is the common form of the idea in Java code.
  • The failing block uses Object.clone for the prototype pattern on a class that does not implement Cloneable. The method compiles, because clone is declared on Object, but it throws CloneNotSupportedException at run time. A copy constructor or a copy method that builds the new object field by field avoids the check, and makes the depth of the copy explicit.
#include <stdio.h>
#include <string.h>

/* An object: a parent pointer and a small table of named slots. */
struct obj;
typedef void (*method)(const struct obj *self);

struct slot {
    const char *name;
    int value;
    method fn;
};

struct obj {
    const struct obj *parent;
    int n;
    struct slot slots[4];
};

static const struct slot *lookup(const struct obj *o, const char *name)
{
    for (; o != NULL; o = o->parent) /* walk the delegation chain */
        for (int i = 0; i < o->n; i++)
            if (strcmp(o->slots[i].name, name) == 0)
                return &o->slots[i];
    return NULL;
}

static void set(struct obj *o, const char *name, int value, method fn)
{
    for (int i = 0; i < o->n; i++)
        if (strcmp(o->slots[i].name, name) == 0) {
            o->slots[i].value = value;
            o->slots[i].fn = fn;
            return;
        }
    o->slots[o->n++] = (struct slot){name, value, fn};
}

static int get(const struct obj *o, const char *name) { return lookup(o, name)->value; }
static void send(const struct obj *o, const char *name) { lookup(o, name)->fn(o); }

static void describe_round(const struct obj *s) { printf("(%d, %d)", get(s, "x"), get(s, "y")); }
static void describe_angle(const struct obj *s) { printf("<%d %d>", get(s, "x"), get(s, "y")); }

int main(void)
{
    struct obj traits = {0}, origin = {.parent = &traits}, p = {.parent = &origin};
    set(&traits, "describe", 0, describe_round);
    set(&origin, "x", 0, NULL);
    set(&origin, "y", 0, NULL);
    set(&p, "x", 3, NULL); /* shadows origin's x */

    send(&origin, "describe");
    printf(" ");
    send(&p, "describe");
    printf("\n");
    set(&traits, "describe", 0, describe_angle); /* one change, every object sees it */
    send(&origin, "describe");
    printf(" ");
    send(&p, "describe");
    printf("\n");
    return 0;
}
Output
(0, 0) (3, 0)
<0 0> <3 0>
  • Verdict: absent. C has structs with fixed members and no dispatch. A prototype object is a struct with a parent pointer and a table of named slots, and a lookup function walks the parent chain. A method slot holds a function pointer that takes the receiver as its argument. Changing a slot in the shared parent changes the behavior of every object that delegates to it.
var traits = new Proto(null);
traits["describe"] = (Func<Proto, string>)(o => $"({o["x"]}, {o["y"]})");
var origin = new Proto(traits) { ["x"] = 0, ["y"] = 0 };

var p = new Proto(origin) { ["x"] = 3 };  // p delegates to origin; x shadows origin's
Console.WriteLine($"{origin.Send("describe")} {p.Send("describe")}");

traits["describe"] = (Func<Proto, string>)(o => $"<{o["x"]} {o["y"]}>");
Console.WriteLine($"{origin.Send("describe")} {p.Send("describe")}");
Console.WriteLine($"{p.Has("y")} {p.Parent == origin}");

// An object with its own slots and a parent to delegate to.
class Proto(Proto? parent)
{
    readonly Dictionary<string, object> slots = new();

    public Proto? Parent => parent;

    public bool Has(string name) => slots.ContainsKey(name);

    public object this[string name]
    {
        get
        {
            for (var o = this; o != null; o = o.Parent)
            {
                if (o.slots.TryGetValue(name, out var v)) return v;
            }
            throw new KeyNotFoundException($"no slot {name}");
        }
        set => slots[name] = value;  // writes always go to an own slot
    }

    public string Send(string name) => ((Func<Proto, string>)this[name])(this);
}
Output
(0, 0) (3, 0)
<0 0> <3 0>
False True

This code runs but gives a wrong answer on purpose.

var prototype = new Form { Name = "form", Fields = ["id"] };

var login = prototype.Clone();  // copy the prototype
login.Name = "login";
login.Fields.Add("password");

Console.WriteLine($"{login.Name}: {string.Join(", ", login.Fields)}");
Console.WriteLine($"{prototype.Name}: {string.Join(", ", prototype.Fields)}");

class Form
{
    public string Name = "";
    public List<string> Fields = [];

    public Form Clone() => (Form)MemberwiseClone();  // copies the fields, not the list
}
Output
login: id, password
form: id, password
  • Verdict: absent. C# objects take their members from their class. The run block builds prototype objects from a dictionary of slots and a parent, with an indexer that reads through the chain and writes to the object itself. ExpandoObject and DynamicObject give objects whose members change at run time through dynamic, but they have no parent link of their own.
  • The wrong block copies a prototype with MemberwiseClone, which makes a shallow copy. The clone gets its own Name but shares the Fields list with the prototype, so adding a field to login changes the prototype as well. A clone method must copy each mutable member, here with new List<string>(Fields).
JavaScriptGitHub
const pointTraits = {  // behavior shared by all points
  describe() { return `(${this.x}, ${this.y})`; },
  moved(dx, dy) { return Object.assign(Object.create(pointTraits), { x: this.x + dx, y: this.y + dy }); },
};

const origin = Object.create(pointTraits);  // an object whose prototype is pointTraits
origin.x = 0;
origin.y = 0;

const p = Object.create(origin);  // p delegates to origin
p.x = 3;                          // an own property shadows origin.x
console.log(p.describe(), Object.keys(p), Object.getPrototypeOf(p) === origin);

pointTraits.describe = function () { return `<${this.x} ${this.y}>`; };
console.log(p.describe(), p.moved(1, 1).describe());  // one change, every point sees it

// Class syntax builds the same structure: methods live on C.prototype.
class Point {
  constructor(x, y) { this.x = x; this.y = y; }
  describe() { return `[${this.x} ${this.y}]`; }
}
const r = new Point(1, 2);
console.log(typeof Point, Object.getPrototypeOf(r) === Point.prototype,
  Object.hasOwn(r, "describe"), r.describe());

Object.setPrototypeOf(r, pointTraits);  // change the prototype of one object
console.log(r.describe());
Output
(3, 0) [ 'x' ] true
<3 0> <4 1>
function true false [1 2]
<1 2>

This code runs but gives a wrong answer on purpose.

const formProto = { fields: [] };  // one array, on the prototype

const login = Object.create(formProto);
const signup = Object.create(formProto);
login.fields.push("password");  // reads fields from the prototype, then changes it
signup.fields.push("email");

console.log(login.fields, signup.fields);
Output
[ 'password', 'email' ] [ 'password', 'email' ]
  • Verdict: native. Every object has a prototype, another object or null, and a property read walks the chain of prototypes until it finds the name. Object.create makes an object with a given prototype, and Object.getPrototypeOf and Object.setPrototypeOf read and change the link. A write creates an own property that shadows the prototype's. Class syntax builds the same structure: a class is a constructor function, its methods live on its prototype object, and each instance delegates to that object.
  • The wrong block puts an array on the prototype. login.fields.push reads fields, finds it on the prototype and changes that one array, because only an assignment to login.fields would create an own property. Both objects then show both fields. Keep mutable state in own properties, set in a constructor or a factory function, and keep only methods and constants on the prototype.
package main

import "fmt"

// Obj has its own slots and a parent to delegate to.
type Obj struct {
	parent *Obj
	slots  map[string]any
}

func New(parent *Obj) *Obj { return &Obj{parent, map[string]any{}} }

func (o *Obj) Get(name string) any {
	for x := o; x != nil; x = x.parent {
		if v, ok := x.slots[name]; ok {
			return v
		}
	}
	panic("no slot " + name)
}

func (o *Obj) Set(name string, v any) *Obj { o.slots[name] = v; return o }

func (o *Obj) Send(name string) string { return o.Get(name).(func(*Obj) string)(o) }

func main() {
	traits := New(nil).Set("describe", func(o *Obj) string {
		return fmt.Sprintf("(%v, %v)", o.Get("x"), o.Get("y"))
	})
	origin := New(traits).Set("x", 0).Set("y", 0)
	p := New(origin).Set("x", 3) // p delegates to origin

	fmt.Println(origin.Send("describe"), p.Send("describe"))
	traits.Set("describe", func(o *Obj) string {
		return fmt.Sprintf("<%v %v>", o.Get("x"), o.Get("y"))
	})
	fmt.Println(origin.Send("describe"), p.Send("describe"))
}
Output
(0, 0) (3, 0)
<0 0> <3 0>

This code runs but gives a wrong answer on purpose.

package main

import "fmt"

type Form struct {
	Name   string
	Fields map[string]bool
}

func main() {
	prototype := Form{Name: "form", Fields: map[string]bool{"id": true}}

	login := prototype // a struct copy: the map header is copied, not the map
	login.Name = "login"
	login.Fields["password"] = true

	fmt.Println(login.Name, len(login.Fields))
	fmt.Println(prototype.Name, len(prototype.Fields))
}
Output
login 2
form 2
  • Verdict: absent. Go types are fixed at compile time, and struct embedding promotes the fields and methods of an embedded value, which is delegation decided by the compiler, not by a link that can change. The run block builds prototype objects from a map of slots and a parent pointer, with functions stored as values and a type assertion to call them.
  • The wrong block clones a struct by assignment. The copy gets its own Name, but a map value is a reference to the map, so both structs share one map, and the new field shows in the prototype. Use maps.Clone for each map field, or write a clone method.
RustGitHub
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

#[derive(Clone)]
enum Slot {
    Int(i64),
    Method(Rc<dyn Fn(&Obj) -> String>),
}

// An object: shared, mutable slots and an optional parent.
#[derive(Clone)]
struct Obj(Rc<Inner>);

struct Inner {
    parent: Option<Obj>,
    slots: RefCell<HashMap<String, Slot>>,
}

impl Obj {
    fn new(parent: Option<&Obj>) -> Obj {
        Obj(Rc::new(Inner { parent: parent.cloned(), slots: RefCell::new(HashMap::new()) }))
    }

    fn set(&self, name: &str, v: Slot) -> &Obj {
        self.0.slots.borrow_mut().insert(name.to_string(), v);
        self
    }

    fn get(&self, name: &str) -> Slot {
        let mut o = Some(self);
        while let Some(x) = o {
            if let Some(v) = x.0.slots.borrow().get(name) {
                return v.clone();
            }
            o = x.0.parent.as_ref();
        }
        panic!("no slot {name}")
    }

    fn int(&self, name: &str) -> i64 {
        match self.get(name) {
            Slot::Int(n) => n,
            Slot::Method(_) => panic!("{name} is a method"),
        }
    }

    fn send(&self, name: &str) -> String {
        match self.get(name) {
            Slot::Method(f) => f(self),
            Slot::Int(_) => panic!("{name} is not a method"),
        }
    }
}

fn main() {
    let traits = Obj::new(None);
    traits.set("describe", Slot::Method(Rc::new(|o| format!("({}, {})", o.int("x"), o.int("y")))));
    let origin = Obj::new(Some(&traits));
    origin.set("x", Slot::Int(0)).set("y", Slot::Int(0));
    let p = Obj::new(Some(&origin));
    p.set("x", Slot::Int(3)); // p delegates to origin

    println!("{} {}", origin.send("describe"), p.send("describe"));
    traits.set("describe", Slot::Method(Rc::new(|o| format!("<{} {}>", o.int("x"), o.int("y")))));
    println!("{} {}", origin.send("describe"), p.send("describe"));
}
Output
(0, 0) (3, 0)
<0 0> <3 0>
  • Verdict: absent. Rust types and their methods are fixed at compile time, and the language has no inheritance between structs. A prototype object needs shared ownership of the parent, Rc, and slots that can change after the object is shared, RefCell, with an enum for the kinds of value a slot holds. The run block builds this, and Clone on Obj copies only the pointer, so clones of the handle see the same object.
  • Ordinary Rust code gets the reuse that prototypes give through traits with default methods and through composition, which the compiler checks.
  • Delegation and concatenation. Delegation shares the parent, so later changes to the parent show in every child. Concatenation copies all properties into the new object, so each object is complete and independent. Antero Taivalsaari's Kevo used concatenation.
  • The prototype design pattern. In class-based languages, a factory keeps configured objects and makes new ones by copying them. The pattern keeps the copying of prototype languages without the delegation.
  • Class inheritance. Classes put structure and behavior in a separate kind of entity, and objects find methods through their class. See class inheritance.
  • Dynamic dispatch. A prototype chain is one way to decide at run time which code a call runs. See dynamic dispatch.
  • Mixins and traits. Several languages compose behavior from small units of methods. JavaScript programs copy methods into a prototype with Object.assign to do this.
  • Metatables. Lua attaches a table of hooks to a table, and the __index hook gives delegation to another table or to a function.
  • Hidden classes. Fast JavaScript engines group objects with the same layout under one internal map, a technique from the Self compiler, so that property access can be as fast as a field read in a class-based language.

Pitfalls

  • Mutable data on the prototype. An array or object stored on a prototype is shared by every object that delegates to it. Changing it through one object changes it for all. Set mutable state on each object in its constructor.
  • Shallow clones. Copying a prototype copies its references, so the clone shares the nested lists and maps of the original. The wrong blocks of the Python, C# and Go files show this. Copy each mutable part, or use a deep copy.
  • Changing built-in prototypes. Adding a method to Array.prototype or Object.prototype in JavaScript changes every array or object in the program, including those of libraries, and can clash with later versions of the language. Use functions or subclasses instead.
  • Inherited properties in loops. A for...in loop in JavaScript visits inherited enumerable properties as well as own ones. Use Object.keys or Object.hasOwn to see only the object's own properties.
  • Changing the parent of a live object. Object.setPrototypeOf on an object that is in use makes engines discard their optimizations for it, and code that read the old chain sees different behavior. Set the prototype when the object is created.
  • Long chains. Each level of a chain is one more lookup for a property that is far up or missing. Keep chains short.

Cost

A property read in a naive implementation searches each object of the chain in turn, so its cost grows with the depth of the chain and the number of properties at each level. Modern engines remove most of this cost. The Self compiler introduced maps, now called hidden classes or shapes, which record the layout of objects created the same way, and inline caches, which remember at each call site where the property was found the last time. With these, a property read in V8 or SpiderMonkey costs a check of the shape and a load at a fixed offset. Changing an object's shape or prototype in a hot path makes the caches miss and costs a slow lookup. Each object stores one reference to its parent, and shared methods cost no memory per object.

History

Henry Lieberman described prototypes with delegation in 1986, in a paper on implementing shared behavior with prototypical objects, which grew from his work on actor languages at MIT. David Ungar and Randall Smith designed Self at Xerox PARC and published it in 1987, as a language with "prototypes, slots, and behavior" and no classes.1 The Self project at Stanford and Sun Microsystems built the techniques that made such a dynamic language fast, among them maps, inline caches and adaptive compilation, and Lars Bak and other members of the team later used them in the HotSpot Java virtual machine and the V8 JavaScript engine.

Brendan Eich created JavaScript at Netscape in 1995 with prototypes taken from Self and syntax that looked like Java. NewtonScript, for the Apple Newton in 1993, also used prototypes, Steve Dekorte's Io followed in 2002, and Lua 5.0 added metatables in 2003, which programs use for delegation between tables. ECMAScript 5 added Object.create in 2009, which gave programs the prototype link without constructor functions, and ECMAScript 2015 added class syntax as a layer on top of the same chain.2

References

  1. David Ungar and Randall B. Smith, SELF: The Power of Simplicity, Lisp and Symbolic Computation 4(3), 1991, Abstract; Section 2
  2. Inheritance and the prototype chain, MDN Web Docs, Inheriting properties
  3. Object.create(), MDN Web Docs, Description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/E0G8GA/text.yaml