Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Prototype-based Programming with JavaScript

7,853 views

Published on

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.

Published in: Technology
  • Be the first to comment

Prototype-based Programming with JavaScript

  1. 1. 3. Prototype-based Programming
  2. 2. 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
  3. 3. PS — Prototype-based Programming 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 © A. Lienhard, O. Nierstrasz 3.3
  4. 4. 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
  5. 5. 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
  6. 6. PS — Prototype-based Programming Class- vs. Prototype-based Class-based: Prototype-based: > Classes share methods and > No classes, only objects define common properties > Objects define their own > Inheritance along class chain properties and methods > Instances have exactly the > Objects delegate to their properties and behavior prototype(s) defined by their class > Any object can be the > Structure typically cannot be prototype of another object changed at runtime Prototype-based languages unify objects and classes © A. Lienhard, O. Nierstrasz 3.6
  7. 7. 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): > JavaScript, Self, Io, NewtonScript, Omega, Cecil, Lua, Object-Lisp, Examplars, Agora, ACT-I, Kevo, Moostrap, Obliq, Garnet © A. Lienhard, O. Nierstrasz 3.7
  8. 8. 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
  9. 9. PS — Prototype-based Programming 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 © A. Lienhard, O. Nierstrasz 3.9
  10. 10. PS — Prototype-based Programming Syntax // single line comment Comments: /* multi line comment */ First character must be a letter, _, or $; subsequent characters Identifiers: can be digits: i, v17, $str, __proto__ ‘a string’, “another string”, “that’s also a string” Basic literals: 17, 6.02e-32 true, false, null, undefined var point = { x:1, y:2 } empty: {} Object literals: nested: var rect = { upperLeft: { x:1, y:2 }, lowerRight: { x:4, y:5 } } Function literals: var square = function(x) { return x*x; } [1,2,3] Array literals: [] assignement: = Operators: equal: == strict equal: === © A. Lienhard, O. Nierstrasz 3.10
  11. 11. PS — Prototype-based Programming Object Properties var book = { title:’JavaScript’ }; Reading properties book.title; //=>’JavaScript’ Adding new properties book.author = ‘J. Doe’; (at runtime) ‘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 © A. Lienhard, O. Nierstrasz 3.11
  12. 12. PS — Prototype-based Programming Methods Methods are just functions var obj = { counter:1 }; that are assigned to obj.increment = function(amount) { properties of an object this.counter += amount; }; At runtime the keyword this is obj.increment(16); bound to the object of the method obj.counter; //=> 17 Accessing (vs. executing) var f = obj.increment; methods typeof f; //=> ‘function’ Property and method slots are unified. Functions are first-class objects. © A. Lienhard, O. Nierstrasz 3.12
  13. 13. 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
  14. 14. 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 oldRect = { width:10, height:3 }; var newRect = {}; newRect.__proto__ = oldRect; ‘width’ in newRect; //=>true Local vs. inherited newRect.hasOwnProperty(‘width’); //=>false properties Binding not found in object, newRect.width; //=>10 then lookup in prototype newRect.foo; //=>undefined © A. Lienhard, O. Nierstrasz 3.14
  15. 15. 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. 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! © A. Lienhard, O. Nierstrasz 3.15
  16. 16. 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
  17. 17. PS — Prototype-based Programming Constructor Functions Constructors are functions that are used with the new operator to create objects function Rectangle(w, h) { this.width = w; this.height = h; this.area = function() { return this.width * this.height; }; The operator new creates an }; object and binds it to this in the constructor. By default the rect = new Rectangle(3,4); return value is the new object. rect.area(); //=>12 © A. Lienhard, O. Nierstrasz 3.17
  18. 18. 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 function Rectangle(w, h) { method for each object, add this.width = w; one to the prototype this.height = h; }; Rectangle.prototype.area = function() { return this.width * this.height; }; © A. Lienhard, O. Nierstrasz 3.18
  19. 19. PS — Prototype-based Programming 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(); © A. Lienhard, O. Nierstrasz 3.19
  20. 20. PS — Prototype-based Programming Object Model Notice, this figure is incomplete... For example: Rectangle.__proto__ === Function.prototype What is Function.__proto__? What is Function.__proto__.__proto__? © A. Lienhard, O. Nierstrasz 3.20
  21. 21. PS — Prototype-based Programming Predefined Objects > Global functions: Array, Boolean, Date, Error, Function, Number, Object, String,... eval, parseInt, ... > Global objects: Math © A. Lienhard, O. Nierstrasz 3.21
  22. 22. PS — Prototype-based Programming Extending Predefined Objects Extending all objects Object.prototype.inspect = function() { alert(this); The last object in the }; prototype chain of 'a string'.inspect(); every object is true.inspect(); Object.prototype (new Date()).inspect(); Array.prototype.map = function(f) { Extending arrays 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] © A. Lienhard, O. Nierstrasz 3.22
  23. 23. PS — Prototype-based Programming The arguments object arguments object function concat(separator) { var result = ‘’; for (var i = 1; i < arguments.length; i++) you can call a function result += arguments[i] + separator; return result; with more arguments }; than it is formally concat(";", "red", "orange", "blue"); declared to accept //=>"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(); f(); f.count; //=>3 © A. Lienhard, O. Nierstrasz 3.23
  24. 24. 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
  25. 25. PS — Prototype-based Programming 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 © A. Lienhard, O. Nierstrasz 3.25
  26. 26. 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 f(x) { function is created, the var y = 1; current scope chain is return function() { return x + y; }; }; saved. Hence, the scope closure = f(2); of f(x) continues to exist var y = 99; even after f(x) returned. closure(); //=>3 © A. Lienhard, O. Nierstrasz 3.26
  27. 27. 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
  28. 28. PS — Prototype-based Programming 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) { Only check() and if (this.check(oldPwrd)) { reset() have access to password = newPwrd; the variable password. }; }; }; Notice, password is a login = new Login(‘Doe’,’xyz’); local variable of the login.username; //=>’Doe’ constructor, not a property login.password; //=>undefined of the created object! login.reset(‘xyz’, 17); login.check(17); //=>true © A. Lienhard, O. Nierstrasz 3.28
  29. 29. 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
  30. 30. PS — Prototype-based Programming 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 © A. Lienhard, O. Nierstrasz 3.30
  31. 31. 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
  32. 32. PS — Prototype-based Programming 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 © A. Lienhard, O. Nierstrasz 3.32
  33. 33. 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
  34. 34. 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
  35. 35. PS — Prototype-based Programming License > http://creativecommons.org/licenses/by-sa/2.5/ Attribution-ShareAlike 2.5 You 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 resulting work 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. © A. Lienhard, O. Nierstrasz 3.35

×