35
3. Prototype-based Programming

Prototype-based Programming with JavaScript

Embed Size (px)

DESCRIPTION

This are the slides from a 2 hour lecture introducing object-oriented prototype-based programming. It includes an introduction to JavaScript, delegation, constructors, and closures.

Citation preview

Page 1: Prototype-based Programming with JavaScript

3. Prototype-based Programming

Page 2: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.6

Class- vs. Prototype-based

> Classes share methods anddefine common properties

> Inheritance along class chain> Instances have exactly the

properties and behaviordefined by their class

> Structure typically cannot bechanged 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.10

Syntax

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

First character must be a letter, _, or $; subsequent characterscan be digits: i, v17, $str, __proto__Identifiers:

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

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

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

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

Object literals:

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

Basic literals:

// single line comment/* multiline comment */

Comments:

Page 11: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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 functionsthat are assigned toproperties of an object

Accessing (vs. executing)methods

At runtime the keyword this isbound to the object of the method

Page 13: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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 allowsone 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. inheritedproperties

Page 15: Prototype-based Programming with JavaScript

© 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 ofnewRect, the receiver, rather than in oldRect, theobject to which the message area() is delegated!

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

Page 16: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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 anobject and binds it to this inthe constructor. By default thereturn value is the new object.

Constructors are functions that are used with the newoperator to create objects

Page 18: Prototype-based Programming with JavaScript

© 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 newmethod for each object, addone 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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 theprototype chain ofevery object isObject.prototype

Page 23: Prototype-based Programming with JavaScript

© 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 functionvar f = function() { if (!arguments.callee.count) { arguments.callee.count = 0; }; arguments.callee.count++; };f(); f(); f();f.count; //=>3

you can call a functionwith more argumentsthan it is formallydeclared to accept

Page 24: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.25

Variable Scopes

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

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

> Identifier resolution:lookup along scope chain

Page 26: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.26

Closures

> Functions are lexically scoped (rather thandynamically). Functions are executed in the scope inwhich 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 anonymousfunction is created, thecurrent scope chain issaved. Hence, the scopeof f(x) continues to existeven after f(x) returned.

Page 27: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.27

Closures

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

Page 28: Prototype-based Programming with JavaScript

© 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() andreset() have access tothe variable password.

Notice, password is alocal variable of theconstructor, not a propertyof the created object!

Page 29: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.29

Closures and Objects

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

Page 30: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© 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: Prototype-based Programming with JavaScript

© A. Lienhard, O. Nierstrasz

PS — Prototype-based Programming

3.35

License

> http://creativecommons.org/licenses/by-sa/2.5/

Attribution-ShareAlike 2.5You are free:• to copy, distribute, display, and perform the work• to make derivative works• to make commercial use of the work

Under the following conditions:

Attribution. You must attribute the work in the manner specified by the author or licensor.

Share Alike. If you alter, transform, or build upon this work, you may distribute the resultingwork only under a license identical to this one.

• For any reuse or distribution, you must make clear to others the license terms of this work.• Any of these conditions can be waived if you get permission from the copyright holder.

Your fair use and other rights are in no way affected by the above.