35
3. Prototype-based Programming

3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap Class- vs. prototype-based languages Objects,

  • View
    218

  • Download
    1

Embed Size (px)

Citation preview

Page 1: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

3. Prototype-based Programming

Page 2: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.2

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 3: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.3

References

> JavaScript: The Definitive Guide, D. Flanagan, O’Reilly, 5th edition

> JavaScript Guide & Reference, Mozilla Developer Center,

http://developer.mozilla.org/en/docs/JavaScript

> Using Prototypical Objects to Implement Shared Behavior in Object

Oriented Systems, H. Lieberman, OOPSLA’86

> ECMAScript Language Specification — 3rd edition, http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Page 4: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.4

Object-oriented Languages

program = objects + messages

Good for encapsulation of state and behavior

Two object-oriented modelsClass-based: code reuse through inheritancePrototype-based: code reuse through delegation

Page 5: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.5

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 6: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.6

Class- vs. 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

Class-based: Prototype-based:

> 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

Page 7: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.7

Prototype-based Languages

No classes simpler descriptions of objectsExamples first (vs. abstraction first)

Fewer concepts simpler programming model

Many languages (but only few used outside research):> JavaScript, Self, Io, NewtonScript, Omega, Cecil, Lua,

Object-Lisp, Examplars, Agora, ACT-I, Kevo, Moostrap, Obliq, Garnet

Page 8: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.8

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 9: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.9

What is JavaScript?

> 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

Page 10: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.10

Syntax

Comments:// single line comment/* multiline comment */

Identifiers: First character must be a letter, _, or $; subsequent characters can be digits: i, v17, $str, __proto__

Basic literals:‘a string’, “another string”, “that’s also a string”17, 6.02e-32 true, false, null, undefined

Object literals:

var point = { x:1, y:2 }empty: {}nested: var rect = { upperLeft: { x:1, y:2 },

lowerRight: { x:4, y:5 } }

Function literals: var square = function(x) { return x*x; }

Array literals: [1,2,3][]

Operators: assignement: =equal: == strict equal: ===

Page 11: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.11

Object Properties

var book = { title:’JavaScript’ };

book.title; //=>’JavaScript’

Adding new properties (at runtime)

Reading properties

book.author = ‘J. Doe’;‘author’ in book; //=>true

Inspecting objects var result = ‘’;for (var name in book) { result += name + ‘=’; result += book[name] + ‘ ’;};//=>title=JavaScript author=J. Doe

Deleting properties delete book.title;‘title’ in book; //=>false

Page 12: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.12

Methods

var obj = { counter:1 };obj.increment = function(amount) { this.counter += amount;};obj.increment(16);obj.counter; //=> 17

Property and method slots are unified. Functions are first-class objects.

var f = obj.increment;

typeof f; //=> ‘function’

Methods are just functions that are assigned to properties of an object

Accessing (vs. executing) methods

At runtime the keyword this is bound to the object of the method

Page 13: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.13

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 14: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.14

Delegation

var oldRect = { width:10, height:3 };var newRect = {};newRect.__proto__ = oldRect;

An object delegates to its prototype object (the Mozilla interpreter allows one to access the prototype through the property __proto__)

newRect.width; //=>10newRect.foo; //=>undefined

Mechanism to share data and behavior is called delegation

Binding not found in object, then lookup in prototype

‘width’ in newRect; //=>truenewRect.hasOwnProperty(‘width’); //=>false

Local vs. inherited properties

Page 15: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.15

Delegation of Messages

newRect.width = 100;oldRect.area = function() { return this.width * this.height;};newRect.area(); //=>300

The method area() is executed in the context of newRect, the receiver, rather than in oldRect, the object to which the message area() is delegated!

The key aspect of prototype delegation is that this in the prototype is bound to the receiver of the original message.

Page 16: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.16

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 17: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.17

Constructor Functions

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

The operator new creates an object and binds it to this in the constructor. By default the return value is the new object.

Constructors are functions that are used with the new operator to create objects

Page 18: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.18

Constructor.prototype

function Rectangle(w, h) { this.width = w; this.height = h;};Rectangle.prototype.area = function() { return this.width * this.height;};

Instead of creating a new method for each object, add one to the 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)

Page 19: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.19

Constructor.prototype

...

function ColoredRectangle(w, h, c) { this.width = w; this.height = h; this.color = c;};ColoredRectangle.prototype = new Rectangle(0,0);coloredRect = new ColoredRectangle(3,4,'red');coloredRect.area();

Page 20: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.20

Object Model

Notice, this figure is incomplete... For example:Rectangle.__proto__ === Function.prototypeWhat is Function.__proto__?What is Function.__proto__.__proto__?

Page 21: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.21

Predefined Objects

> Global functions: Array, Boolean, Date, Error, Function, Number, Object, String,... eval, parseInt, ...

> Global objects: Math

Page 22: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.22

Extending Predefined Objects

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]

Object.prototype.inspect = function() { alert(this);};'a string'.inspect();true.inspect();(new Date()).inspect();

Extending all objects

Extending arrays

The last object in the prototype chain of every object is Object.prototype

Page 23: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.23

The arguments object

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 object

arguments.callee returns the currently executing function

var f = function() { if (!arguments.callee.count) { arguments.callee.count = 0; }; arguments.callee.count++; };f(); f(); f();f.count; //=>3

you can call a function with more arguments than it is formally declared to accept

Page 24: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.24

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 25: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.25

Variable Scopes

> The scope of a variable is the region of the program in which it is defined

> Scopes in JavaScript— function— global— no block-level scope(!)

> Identifier resolution:lookup along scope chain

Page 26: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.26

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

function f(x) { var y = 1; return function() { return x + y; };};closure = f(2);var y = 99;closure(); //=>3

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.

Page 27: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.27

Closures

A closure is a function that can have free variables together with an environment that binds those variables (that "closes" the expression).

Page 28: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.28

Closures and Objects

By default all properties and methods are public.Using closures, properties and methods can be made private.

function Login(string, anotherString) { this.username = string; var password = anotherString; this.check = function(pwrd) { return password == pwrd; }; this.reset = function(oldPwrd,newPwrd) { if (this.check(oldPwrd)) { password = newPwrd; }; };};login = new Login(‘Doe’,’xyz’);login.username; //=>’Doe’login.password; //=>undefinedlogin.reset(‘xyz’, 17);login.check(17); //=>true

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!

Page 29: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.29

Closures and Objects

Both functions close over the same environment, the execution context of Login(), enabling them to communicate privately by altering that environment.

Page 30: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.30

Other JavaScript Features

> Regular Expressions> Client-side JavaScript (DOM, AJAX, ...)> Processing XML with E4X (introduced in v1.6)> Iterators and Generators (introduced in v1.7)

> JavaScript integration into Java 6 with Rhino

Page 31: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.31

Roadmap

> Class- vs. prototype-based languages> Objects, properties and methods> Delegation> Constructors> Closures> Other prototype-based languages

Page 32: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.32

Variation Points

> Basic mechanisms— Object creation: ex-nihilo, cloning, extension

— Object representation (slots in JavaScript, Self, NewstonScript vs. attributes and methods in Agora, Kevo)

> Delegation— Double delegation in Io/NewtonScript

— Multiple prototypes (aka. parents) in Self

— Can prototype link be changed at runtime?

> Organization of programs (prototypical instance, traits, ...)

program = objects + messages + delegation

Page 33: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.33

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?

Page 34: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.34

Can you answer these questions?

What is the prototype of the global object Function? How would you implement private static properties?

Page 35: 3. Prototype-based Programming. © A. Lienhard, O. Nierstrasz PS — Prototype-based Programming 3.2 Roadmap  Class- vs. prototype-based languages  Objects,

© Oscar Nierstrasz

ST — Introduction

1.35

Attribution-ShareAlike 3.0 UnportedYou are free:

to Share — to copy, distribute and transmit the workto 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.

License

http://creativecommons.org/licenses/by-sa/3.0/