3 Prototypebased Programming PS Prototypebased Programming Roadmap Class
3. Prototype-based Programming
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 2
PS — Prototype-based Programming References > Java. Script: The Definitive Guide, D. Flanagan, O’Reilly, 5 th edition > Java. Script Guide & Reference, Mozilla Developer Center, http: //developer. mozilla. org/en/docs/Java. Script > > Using Prototypical Objects to Implement Shared Behavior in Object Oriented Systems, H. Lieberman, OOPSLA’ 86 ECMAScript Language Specification — 3 rd edition, http: //www. ecmainternational. org/publications/files/ECMA-ST/Ecma-262. pdf © A. Lienhard, O. Nierstrasz 3. 3
PS — Prototype-based Programming Object-oriented Languages program = objects + messages Good for encapsulation of state and behavior Two object-oriented models Class-based: code reuse through inheritance Prototype-based: code reuse through delegation © A. Lienhard, O. Nierstrasz 3. 4
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 5
PS — Prototype-based Programming Class- vs. Prototype-based Class-based: > > Prototype-based: Classes share methods and define common properties Inheritance along class chain Instances have exactly the properties and behavior defined by their class Structure typically cannot be changed at runtime > > No classes, only objects Objects define their own properties and methods Objects delegate to their prototype(s) Any object can be the prototype of another object Prototype-based languages unify objects and classes © A. Lienhard, O. Nierstrasz 3. 6
PS — Prototype-based Programming Prototype-based Languages No classes simpler descriptions of objects Examples first (vs. abstraction first) Fewer concepts simpler programming model Many languages (but only few used outside research): > Java. Script, Self, Io, Newton. Script, Omega, Cecil, Lua, Object -Lisp, Examplars, Agora, ACT-I, Kevo, Moostrap, Obliq, Garnet © A. Lienhard, O. Nierstrasz 3. 7
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 8
PS — Prototype-based Programming What is Java. Script? > Introduced in 1995 by Netscape > Minimal object model: — everything is an object (almost) — functions are first-class objects, closures > > Prototype-based delegation Dynamically typed, interpreted Platforms: web browsers and servers, Java 6, embedded in various applications (Flash, Photoshop, . . . ) What it is not: — No direct relationship to Java — Not only for scripting web browsers © A. Lienhard, O. Nierstrasz 3. 9
PS — Prototype-based Programming Syntax Comments: // single line comment /* multi line comment */ Identifiers: First character must be a letter, _, or $; subsequent characters can be digits: i, v 17, $str, __proto__ Basic literals: ‘a string’, “another string”, “that’s also a string” 17, 6. 02 e-32 true, false, null, undefined Object literals: var point = { x: 1, y: 2 } empty: {} nested: var rect = { upper. Left: { x: 1, y: 2 }, lower. Right: { x: 4, y: 5 } } Function literals: var square = function(x) { return x*x; } Array literals: Operators: © A. Lienhard, O. Nierstrasz [1, 2, 3] [] assignement: = equal: == strict equal: === 3. 10
PS — Prototype-based Programming Object Properties Reading properties var book = { title: ’Java. Script’ }; Adding new properties (at runtime) book. author = ‘J. Doe’; ‘author’ in book; //=>true Inspecting objects var result = ‘’; for (var name in book) { result += name + ‘=’; result += book[name] + ‘ ’; }; //=>title=Java. Script author=J. Doe Deleting properties © A. Lienhard, O. Nierstrasz book. title; //=>’Java. Script’ delete book. title; ‘title’ in book; //=>false 3. 11
PS — Prototype-based Programming Methods are just functions that are assigned to properties of an object At runtime the keyword this is bound to the object of the method Accessing (vs. executing) methods var obj = { counter: 1 }; obj. increment = function(amount) { this. counter += amount; }; obj. increment(16); obj. counter; //=> 17 var f = obj. increment; typeof f; //=> ‘function’ Property and method slots are unified. Functions are first-class objects. © A. Lienhard, O. Nierstrasz 3. 12
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 13
PS — Prototype-based Programming Delegation Mechanism to share data and behavior is called delegation An object delegates to its prototype object (the Mozilla interpreter allows one to access the prototype through the property __proto__) var old. Rect = { width: 10, height: 3 }; var new. Rect = {}; new. Rect. __proto__ = old. Rect; ‘width’ in new. Rect; //=>true new. Rect. has. Own. Property(‘width’); //=>false Binding not found in object, then lookup in prototype © A. Lienhard, O. Nierstrasz Local vs. inherited properties new. Rect. width; //=>10 new. Rect. foo; //=>undefined 3. 14
PS — Prototype-based Programming Delegation of Messages The key aspect of prototype delegation is that this in the prototype is bound to the receiver of the original message. new. Rect. width = 100; old. Rect. area = function() { return this. width * this. height; }; new. Rect. area(); //=>300 The method area() is executed in the context of new. Rect, the receiver, rather than in old. Rect, the object to which the message area() is delegated! © A. Lienhard, O. Nierstrasz 3. 15
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 16
PS — Prototype-based Programming Constructor Functions Constructors are functions that are used with the new operator to create objects The operator new creates an object and binds it to this in the constructor. By default the return value is the new object. © A. Lienhard, O. Nierstrasz function Rectangle(w, h) { this. width = w; this. height = h; this. area = function() { return this. width * this. height; }; }; rect = new Rectangle(3, 4); rect. area(); //=>12 3. 17
PS — Prototype-based Programming Constructor. prototype > > All objects created with a constructor share the same prototype Each constructor has a prototype property (which is automatically initialized when defining the function) Instead of creating a new method for each object, add one to the prototype © A. Lienhard, O. Nierstrasz function Rectangle(w, h) { this. width = w; this. height = h; }; Rectangle. prototype. area = function() { return this. width * this. height; }; 3. 18
PS — Prototype-based Programming Constructor. prototype. . . function Colored. Rectangle(w, h, c) { this. width = w; this. height = h; this. color = c; }; Colored. Rectangle. prototype = new Rectangle(0, 0); colored. Rect = new Colored. Rectangle(3, 4, 'red'); colored. Rect. area(); © A. Lienhard, O. Nierstrasz 3. 19
PS — Prototype-based Programming Object Model Notice, this figure is incomplete. . . For example: Rectangle. __proto__ === Function. prototype What is Function. __proto__? © A. Lienhard, O. Nierstrasz 3. 20
PS — Prototype-based Programming Predefined Objects > Global functions: Array, Boolean, Date, Error, Function, Number, Object, String, . . . eval, parse. Int, . . . > Global objects: Math © A. Lienhard, O. Nierstrasz 3. 21
PS — Prototype-based Programming Extending Predefined Objects Extending all objects The last object in the prototype chain of every object is Object. prototype Extending arrays © A. Lienhard, O. Nierstrasz Object. prototype. inspect = function() { alert(this); }; 'a string'. inspect(); true. inspect(); (new Date()). inspect(); Array. prototype. map = function(f) { var array = []; for (var n = 0; n < this. length; n++) { if (n in this) { array[n] = f(this[n]); }; }; return array; }; [1. 7, -3. 1, 17]. map(Math. floor); //=>[1, -4, 17] [1. 7, -3. 1, 17]. map(function(x) { return x+1; }); //=>[2. 7, -2. 1, 18] 3. 22
PS — Prototype-based Programming The arguments object you can call a function with more arguments than it is formally declared to accept function concat(separator) { var result = ‘’; for (var i = 1; i < arguments. length; i++) result += arguments[i] + separator; return result; }; concat("; ", "red", "orange", "blue"); //=>"red; orange; blue; " arguments. callee returns the currently executing function var f = function() { if (!arguments. callee. count) { arguments. callee. count = 0; }; arguments. callee. count++; }; f(); f. count; //=>3 © A. Lienhard, O. Nierstrasz 3. 23
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 24
PS — Prototype-based Programming Variable Scopes > The scope of a variable is the region of the program in which it is defined > Scopes in Java. Script — function — global — no block-level scope(!) > Identifier resolution: lookup along scope chain © A. Lienhard, O. Nierstrasz 3. 25
PS — Prototype-based Programming Closures > Functions are lexically scoped (rather than dynamically). Functions are executed in the scope in which they are created, not from which they are called. > Inner functions as closures When the anonymous function is created, the current scope chain is saved. Hence, the scope of f(x) continues to exist even after f(x) returned. © A. Lienhard, O. Nierstrasz function f(x) { var y = 1; return function() { return x + y; }; }; closure = f(2); var y = 99; closure(); //=>3 3. 26
PS — Prototype-based Programming Closures A closure is a function that can have free variables together with an environment that binds those variables (that "closes" the expression). © A. Lienhard, O. Nierstrasz 3. 27
PS — Prototype-based Programming Closures and Objects By default all properties and methods are public. Using closures, properties and methods can be made private. Only check() and reset() have access to the variable password. Notice, password is a local variable of the constructor, not a property of the created object! © A. Lienhard, O. Nierstrasz function Login(string, another. String) { this. username = string; var password = another. String; this. check = function(pwrd) { return password == pwrd; }; this. reset = function(old. Pwrd, new. Pwrd) { if (this. check(old. Pwrd)) { password = new. Pwrd; }; }; }; login = new Login(‘Doe’, ’xyz’); login. username; //=>’Doe’ login. password; //=>undefined login. reset(‘xyz’, 17); login. check(17); //=>true 3. 28
PS — Prototype-based Programming Closures and Objects Both functions close over the same environment, the execution context of Login(), enabling them to communicate privately by altering that environment. © A. Lienhard, O. Nierstrasz 3. 29
PS — Prototype-based Programming Other Java. Script Features > Regular Expressions > Client-side Java. Script (DOM, AJAX, . . . ) > Processing XML with E 4 X (introduced in v 1. 6) > Iterators and Generators (introduced in v 1. 7) > Java. Script integration into Java 6 with Rhino © A. Lienhard, O. Nierstrasz 3. 30
PS — Prototype-based Programming Roadmap > Class- vs. prototype-based languages > Objects, properties and methods > Delegation > Constructors > Closures > Other prototype-based languages © A. Lienhard, O. Nierstrasz 3. 31
PS — Prototype-based Programming Variation Points > Basic mechanisms — Object creation: ex-nihilo, cloning, extension — Object representation (slots in Java. Script, Self, Newston. Script vs. attributes and methods in Agora, Kevo) > Delegation — Double delegation in Io/Newton. Script — Multiple prototypes (aka. parents) in Self — Can prototype link be changed at runtime? > Organization of programs (prototypical instance, traits, . . . ) program = objects + messages + delegation © A. Lienhard, O. Nierstrasz 3. 32
PS — Prototype-based Programming What you should know! What is the difference between delegation and inheritance? Which object is modified when changing the value of a property within a delegated method? How do you extend all objects created with a specific constructor? Where do you define properties that are shared between a group of objects (i. e. , static members in Java)? How does variable scoping work? What is a closure? © A. Lienhard, O. Nierstrasz 3. 33
PS — Prototype-based Programming Can you answer these questions? What is the prototype of the global object Function? How would you implement private static properties? © A. Lienhard, O. Nierstrasz 3. 34
ST — Introduction License http: //creativecommons. org/licenses/by-sa/3. 0/ Attribution-Share. Alike 3. 0 Unported You are free: to Share — to copy, distribute and transmit the work to Remix — to adapt the work Under the following conditions: Attribution. You must attribute the work in the manner specified by the author or licensor (but not in any way that suggests that they endorse you or your use of the work). Share Alike. If you alter, transform, or build upon this work, you may distribute the resulting work only under the same, similar or a compatible license. For any reuse or distribution, you must make clear to others the license terms of this work. The best way to do this is with a link to this web page. Any of the above conditions can be waived if you get permission from the copyright holder. Nothing in this license impairs or restricts the author's moral rights. © Oscar Nierstrasz 1. 35
- Slides: 35