SlideShare a Scribd company logo
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



      >     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
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                  >   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
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
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 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
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
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
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
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 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
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
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
                                     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
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
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
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
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
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
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
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 JavaScript
             — 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 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
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.
                                        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
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 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
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 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
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
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

More Related Content

What's hot (20)

The ruby programming language
The ruby programming languageThe ruby programming language
The ruby programming language
praveen0202
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
Martijn Blankestijn
 
Ruby golightly
Ruby golightlyRuby golightly
Ruby golightly
Eleanor McHugh
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
Javier Gonzalez-Sanchez
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax Definition
Eelco Visser
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
2004 Esug Prototalk
2004 Esug Prototalk2004 Esug Prototalk
2004 Esug Prototalk
bergel
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
schwaa
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Ch08 - Manipulating Data in Strings and Arrays
Ch08 - Manipulating Data in Strings and ArraysCh08 - Manipulating Data in Strings and Arrays
Ch08 - Manipulating Data in Strings and Arrays
dcomfort6819
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Xml Path Language1.0
Xml Path Language1.0Xml Path Language1.0
Xml Path Language1.0
LiquidHub
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
Kevlin Henney
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
monikadeshmane
 
OWL 2 Quick Reference Card Letter Size
OWL 2 Quick Reference Card Letter SizeOWL 2 Quick Reference Card Letter Size
OWL 2 Quick Reference Card Letter Size
Jie Bao
 
Playfulness at Work
Playfulness at WorkPlayfulness at Work
Playfulness at Work
Erin Dees
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
Kevlin Henney
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
meysholdt
 
The ruby programming language
The ruby programming languageThe ruby programming language
The ruby programming language
praveen0202
 
NLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by OrdinaNLJUG University Sessie: Java Reborn, Powered by Ordina
NLJUG University Sessie: Java Reborn, Powered by Ordina
Martijn Blankestijn
 
Model-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax DefinitionModel-Driven Software Development - Language Workbenches & Syntax Definition
Model-Driven Software Development - Language Workbenches & Syntax Definition
Eelco Visser
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
Sujith Kumar
 
2004 Esug Prototalk
2004 Esug Prototalk2004 Esug Prototalk
2004 Esug Prototalk
bergel
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
schwaa
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
Sujith Kumar
 
Ch08 - Manipulating Data in Strings and Arrays
Ch08 - Manipulating Data in Strings and ArraysCh08 - Manipulating Data in Strings and Arrays
Ch08 - Manipulating Data in Strings and Arrays
dcomfort6819
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
Arslan Arshad
 
Xml Path Language1.0
Xml Path Language1.0Xml Path Language1.0
Xml Path Language1.0
LiquidHub
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
Kevlin Henney
 
Chap1introppt2php(finally done)
Chap1introppt2php(finally done)Chap1introppt2php(finally done)
Chap1introppt2php(finally done)
monikadeshmane
 
OWL 2 Quick Reference Card Letter Size
OWL 2 Quick Reference Card Letter SizeOWL 2 Quick Reference Card Letter Size
OWL 2 Quick Reference Card Letter Size
Jie Bao
 
Playfulness at Work
Playfulness at WorkPlayfulness at Work
Playfulness at Work
Erin Dees
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
Kevlin Henney
 
Xbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for JavaXbase - Implementing Domain-Specific Languages for Java
Xbase - Implementing Domain-Specific Languages for Java
meysholdt
 

Viewers also liked (20)

Prototype
PrototypePrototype
Prototype
Aditya Gaur
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
Narendra Sisodiya
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Identifying Traits with Formal Concept Analysis
Identifying Traits with Formal Concept AnalysisIdentifying Traits with Formal Concept Analysis
Identifying Traits with Formal Concept Analysis
lienhard
 
Prototyping user interactions in web apps
Prototyping user interactions in web appsPrototyping user interactions in web apps
Prototyping user interactions in web apps
Patrick NDJIENTCHEU
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
javascript prototype
javascript prototypejavascript prototype
javascript prototype
Hika Maeng
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
Pham Huy Tung
 
CSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle ApproachCSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle Approach
Julie Kuehl
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
Kanchha kaji Prajapati
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
Nick Cooley
 
Smart CSS theming with Sass and Compass
Smart CSS theming with Sass and CompassSmart CSS theming with Sass and Compass
Smart CSS theming with Sass and Compass
Mihaela
 
Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)
Tahmina Khatoon
 
JavaScript OOPs
JavaScript OOPsJavaScript OOPs
JavaScript OOPs
Johnson Chou
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
Naresh Kumar
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
Brian Moschel
 
Sass - Getting Started with Sass!
Sass - Getting Started with Sass!Sass - Getting Started with Sass!
Sass - Getting Started with Sass!
Eric Sembrat
 
Javascript Prototype Visualized
Javascript Prototype VisualizedJavascript Prototype Visualized
Javascript Prototype Visualized
军 沈
 
JavaScript Prototype and Module Pattern
JavaScript Prototype and Module PatternJavaScript Prototype and Module Pattern
JavaScript Prototype and Module Pattern
Narendra Sisodiya
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
Identifying Traits with Formal Concept Analysis
Identifying Traits with Formal Concept AnalysisIdentifying Traits with Formal Concept Analysis
Identifying Traits with Formal Concept Analysis
lienhard
 
Prototyping user interactions in web apps
Prototyping user interactions in web appsPrototyping user interactions in web apps
Prototyping user interactions in web apps
Patrick NDJIENTCHEU
 
Understanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG JuneUnderstanding Object Oriented Javascript - Coffee@DBG June
Understanding Object Oriented Javascript - Coffee@DBG June
Deepu S Nath
 
javascript prototype
javascript prototypejavascript prototype
javascript prototype
Hika Maeng
 
Javascript this keyword
Javascript this keywordJavascript this keyword
Javascript this keyword
Pham Huy Tung
 
CSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle ApproachCSS Sanity with Sass: The Inverted Triangle Approach
CSS Sanity with Sass: The Inverted Triangle Approach
Julie Kuehl
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
Chamnap Chhorn
 
Advanced sass/compass
Advanced sass/compassAdvanced sass/compass
Advanced sass/compass
Nick Cooley
 
Smart CSS theming with Sass and Compass
Smart CSS theming with Sass and CompassSmart CSS theming with Sass and Compass
Smart CSS theming with Sass and Compass
Mihaela
 
Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)Syntactically awesome stylesheets (Sass)
Syntactically awesome stylesheets (Sass)
Tahmina Khatoon
 
Advanced JavaScript Concepts
Advanced JavaScript ConceptsAdvanced JavaScript Concepts
Advanced JavaScript Concepts
Naresh Kumar
 
Sass - Getting Started with Sass!
Sass - Getting Started with Sass!Sass - Getting Started with Sass!
Sass - Getting Started with Sass!
Eric Sembrat
 
Ad

Similar to Prototype-based Programming with JavaScript (20)

javascript
javascript javascript
javascript
Kaya Ota
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
 
Xbase implementing specific domain language for java
Xbase  implementing specific domain language for javaXbase  implementing specific domain language for java
Xbase implementing specific domain language for java
Yash Patel
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
EPAM Systems
 
Object oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingObject oriented programming 2 elements of programming
Object oriented programming 2 elements of programming
Vaibhav Khanna
 
PHP in one presentation
PHP in one presentationPHP in one presentation
PHP in one presentation
Milad Rahimi
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
The Bund language
The Bund languageThe Bund language
The Bund language
Vladimir Ulogov
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
Tarek Abdul-Kader , Android Developer
 
Programming paradigms Techniques_part2.pptx
Programming paradigms Techniques_part2.pptxProgramming paradigms Techniques_part2.pptx
Programming paradigms Techniques_part2.pptx
ssuser5ecd1a
 
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Baltasar García Perez-Schofield
 
Oop basic concepts
Oop basic conceptsOop basic concepts
Oop basic concepts
Swarup Kumar Boro
 
OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
Objective c slide I
Objective c slide IObjective c slide I
Objective c slide I
Diksha Bhargava
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
SahajShrimal1
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Language
dheva B
 
Oopsinphp
OopsinphpOopsinphp
Oopsinphp
NithyaNithyav
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1
mohamedsamyali
 
It Is Possible to Do Object-Oriented Programming in Java
It Is Possible to Do Object-Oriented Programming in JavaIt Is Possible to Do Object-Oriented Programming in Java
It Is Possible to Do Object-Oriented Programming in Java
Kevlin Henney
 
Class 32: Interpreters
Class 32: InterpretersClass 32: Interpreters
Class 32: Interpreters
David Evans
 
javascript
javascript javascript
javascript
Kaya Ota
 
Introduction to object oriented programming
Introduction to object oriented programmingIntroduction to object oriented programming
Introduction to object oriented programming
Abzetdin Adamov
 
Xbase implementing specific domain language for java
Xbase  implementing specific domain language for javaXbase  implementing specific domain language for java
Xbase implementing specific domain language for java
Yash Patel
 
Complete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScriptComplete Notes on Angular 2 and TypeScript
Complete Notes on Angular 2 and TypeScript
EPAM Systems
 
Object oriented programming 2 elements of programming
Object oriented programming 2 elements of programmingObject oriented programming 2 elements of programming
Object oriented programming 2 elements of programming
Vaibhav Khanna
 
PHP in one presentation
PHP in one presentationPHP in one presentation
PHP in one presentation
Milad Rahimi
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
Nilesh Jayanandana
 
Programming paradigms Techniques_part2.pptx
Programming paradigms Techniques_part2.pptxProgramming paradigms Techniques_part2.pptx
Programming paradigms Techniques_part2.pptx
ssuser5ecd1a
 
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...Post-graduate course: Object technology: Prototype-based object-oriented prog...
Post-graduate course: Object technology: Prototype-based object-oriented prog...
Baltasar García Perez-Schofield
 
OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1OOPS (object oriented programming) unit 1
OOPS (object oriented programming) unit 1
AnamikaDhoundiyal
 
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdfconceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
conceptsinobjectorientedprogramminglanguages-12659959597745-phpapp02.pdf
SahajShrimal1
 
Object Oriented Language
Object Oriented LanguageObject Oriented Language
Object Oriented Language
dheva B
 
C# Summer course - Lecture 1
C# Summer course - Lecture 1C# Summer course - Lecture 1
C# Summer course - Lecture 1
mohamedsamyali
 
It Is Possible to Do Object-Oriented Programming in Java
It Is Possible to Do Object-Oriented Programming in JavaIt Is Possible to Do Object-Oriented Programming in Java
It Is Possible to Do Object-Oriented Programming in Java
Kevlin Henney
 
Class 32: Interpreters
Class 32: InterpretersClass 32: Interpreters
Class 32: Interpreters
David Evans
 
Ad

More from lienhard (10)

Chicken
ChickenChicken
Chicken
lienhard
 
Virtual Machines Lecture
Virtual Machines LectureVirtual Machines Lecture
Virtual Machines Lecture
lienhard
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
lienhard
 
OORPT Dynamic Analysis
OORPT Dynamic AnalysisOORPT Dynamic Analysis
OORPT Dynamic Analysis
lienhard
 
Dynamic Object Flow Analysis (PhD Defense)
Dynamic Object Flow Analysis (PhD Defense)Dynamic Object Flow Analysis (PhD Defense)
Dynamic Object Flow Analysis (PhD Defense)
lienhard
 
Rapid Prototyping Of Visualizations Using Mondrian
Rapid Prototyping Of Visualizations Using MondrianRapid Prototyping Of Visualizations Using Mondrian
Rapid Prototyping Of Visualizations Using Mondrian
lienhard
 
Tracking Objects To Detect Feature Dependencies
Tracking Objects To Detect Feature DependenciesTracking Objects To Detect Feature Dependencies
Tracking Objects To Detect Feature Dependencies
lienhard
 
Practical Object-Oriented Back-in-Time Debugging
Practical Object-Oriented Back-in-Time DebuggingPractical Object-Oriented Back-in-Time Debugging
Practical Object-Oriented Back-in-Time Debugging
lienhard
 
Test Blueprints
Test BlueprintsTest Blueprints
Test Blueprints
lienhard
 
Object Flow Analysis
Object Flow AnalysisObject Flow Analysis
Object Flow Analysis
lienhard
 
Virtual Machines Lecture
Virtual Machines LectureVirtual Machines Lecture
Virtual Machines Lecture
lienhard
 
Flow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time DebuggingFlow-Centric, Back-In-Time Debugging
Flow-Centric, Back-In-Time Debugging
lienhard
 
OORPT Dynamic Analysis
OORPT Dynamic AnalysisOORPT Dynamic Analysis
OORPT Dynamic Analysis
lienhard
 
Dynamic Object Flow Analysis (PhD Defense)
Dynamic Object Flow Analysis (PhD Defense)Dynamic Object Flow Analysis (PhD Defense)
Dynamic Object Flow Analysis (PhD Defense)
lienhard
 
Rapid Prototyping Of Visualizations Using Mondrian
Rapid Prototyping Of Visualizations Using MondrianRapid Prototyping Of Visualizations Using Mondrian
Rapid Prototyping Of Visualizations Using Mondrian
lienhard
 
Tracking Objects To Detect Feature Dependencies
Tracking Objects To Detect Feature DependenciesTracking Objects To Detect Feature Dependencies
Tracking Objects To Detect Feature Dependencies
lienhard
 
Practical Object-Oriented Back-in-Time Debugging
Practical Object-Oriented Back-in-Time DebuggingPractical Object-Oriented Back-in-Time Debugging
Practical Object-Oriented Back-in-Time Debugging
lienhard
 
Test Blueprints
Test BlueprintsTest Blueprints
Test Blueprints
lienhard
 
Object Flow Analysis
Object Flow AnalysisObject Flow Analysis
Object Flow Analysis
lienhard
 

Recently uploaded (20)

National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
Can We Use Rust to Develop Extensions for PostgreSQL? (POSETTE: An Event for ...
NTT DATA Technology & Innovation
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 

Prototype-based Programming with JavaScript

  • 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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