OBJECT ORIENTED
                           JAVASCRIPT


                           Rody Middelkoop - WT
Thursday, March 18...
About Objects
  2

           Almost everything written in JavaScript is an object
           Objects can be though of a...
OBJECTS
Thursday, March 18, 2010
Object Literal Notation
  4

          // The old way
          var myObject = new Object();
          myObject.val = “tes...
Object Literal Notation
  5

          // The old way
          var myArray = new Array(1, 30, “Refresh”);


          // ...
Anonymous Functions
  6


          // Using an anonymous function as an argument
          setTimeout( function () {
    ...
Binary Assignment
  7


          Set a default value only if the variable doesn’t have a value yet

          // Traditio...
INNER FUNCTIONS
Thursday, March 18, 2010
Scope: Inner Functions
  9

           Functions can be defined within one another
           Inner functions have acces...
Closures
 10

              Inner functions maintain the scope they enjoyed when
               their parent function was...
Closures
 11


          function delayedAlert (message, delay) {
              setTimeout( function () {
                ...
 Now let’s apply all of this information to a more
       classical view of OOP in JavaScript:
      Constructors

     ...
METHODS
Thursday, March 18, 2010
Public Methods
 14

           One way to create a public method—a function that
            can be freely reference by c...
PROTOTYPE…
Thursday, March 18, 2010
Public methods
 16

          var Person = function(name) {
             this.name = name;
          };
          Person.p...
Prototype
 17

           Each function object has a property called prototype,
            which itself is an object and...
Prototype usage
 18

           say() is a property of the prototype object
           but it behaves as if it's a prope...
Own properties vs. prototype’s
 19




          >>> dude.hasOwnProperty('name');
          true
          >>> dude.hasOwn...
Private Methods
 20

              Private methods are functions that are only accessible
               to methods insid...
Private Methods
 21

            var User = function (name) {
               this.name = name;
                  function ...
“Privileged” Methods
 22

           The term privileged method was coined by Douglas
            Crockford. It is not a ...
“Privileged” Methods
 23


           var User = function (name, age) {
              var year = (new Date()).getFullYear(...
CONSTRUCTORS
Thursday, March 18, 2010
Constructor functions
 25

          var Person = function(name) {
             this.name = name;
             this.getNam...
A naming convention
 26

           MyConstructor
           myFunction




                            CRIA-WT - Rody M...
INHERITANCE
Thursday, March 18, 2010
Parent constructor
 28

          function NormalObject() {
            this.name = 'normal';
            this.getName = f...
Child constructor
 29

          function PreciousObject(){
            this.shiny = true;
            this.round = true;
...
The inheritance
 30

          PreciousObject.prototype =
              new NormalObject();




                          ...
A child object
 31

          var crystal_ball =
             new PreciousObject();
          crystal_ball.name = 'Crystal...
Calling the superclass’ constructor
 32




                           CRIA-WT - Rody Middelkoop

Thursday, March 18, 2010
INHERITANCE BY COPYING
Thursday, March 18, 2010
Two objects
 34

          var shiny = {
             shiny: true,
             round: true
          };
          var nor...
extend()
 35

          function extend(parent, child) {
            for (var i in parent) {
              child[i] = pare...
Inheritance
 36

          extend(normal, shiny);
          shiny.getName(); // "name me"




                           C...
Grand Finale
 37

              Using Scope, Closures, Contexts, and what we’ve
               discussed about OOP, we ca...
Grand Finale
 38


          function User (properties) {
             for ( var i in properties ) { function () {
       ...
Grand Finale
 39

          // …continued

          alert( me.name == null );
          alert( me.getname() == “Bob” );
 ...
References and a big thank you
 40

           Pro JavaScript Techniques, by John Resig
           Douglas Crockford’s
 ...
Upcoming SlideShare
Loading in …5
×

OO JavaScript

2,020 views

Published on

Slides used for the course WebTechnology, part of CRIA.

Published in: Technology
0 Comments
9 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,020
On SlideShare
0
From Embeds
0
Number of Embeds
25
Actions
Shares
0
Downloads
125
Comments
0
Likes
9
Embeds 0
No embeds

No notes for slide

OO JavaScript

  1. 1. OBJECT ORIENTED JAVASCRIPT Rody Middelkoop - WT Thursday, March 18, 2010
  2. 2. About Objects 2  Almost everything written in JavaScript is an object  Objects can be though of as a collection of properties —much like a hash in other languages  JavaScript doesn’t have a concept of classes like other object-oriented languages  Classes are simulated using a concept called prototypal inheritance CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  3. 3. OBJECTS Thursday, March 18, 2010
  4. 4. Object Literal Notation 4 // The old way var myObject = new Object(); myObject.val = “test”; // Using object literal notation var myObject = {   val: “test” }; CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  5. 5. Object Literal Notation 5 // The old way var myArray = new Array(1, 30, “Refresh”); // Using object literal notation var myArray = [1, 30, “Refresh”]; CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  6. 6. Anonymous Functions 6 // Using an anonymous function as an argument setTimeout( function () {  alert( “Refresh” );  }, 1000 );    // Using a function as a variable var myFunc = function () {   alert( “Refresh” );  }; setTimeout(myFunc, 1000); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  7. 7. Binary Assignment 7 Set a default value only if the variable doesn’t have a value yet // Traditional ternary assignment var myVar = myVar ? myVar : 0; // Binary assignment var myVar = myVal || 0; CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  8. 8. INNER FUNCTIONS Thursday, March 18, 2010
  9. 9. Scope: Inner Functions 9  Functions can be defined within one another  Inner functions have access to the outer function’s variables and parameters. function getRandomInt(max) { var randNum = Math.random() * max; function ceil() { return Math.ceil(randNum); } return ceil(); // Notice that no arguments are passed } alert(getRandomInt(5)); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  10. 10. Closures 10  Inner functions maintain the scope they enjoyed when their parent function was called—even after the parent function has terminated.  This allows you to effectively pass variables to functions that may not be called for some time. CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  11. 11. Closures 11 function delayedAlert (message, delay) {   setTimeout( function () {     alert(message);   }, delay); }   // Display a message with a 5 second delay delayedAlert(“Refresh”, 5000); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  12. 12.  Now let’s apply all of this information to a more classical view of OOP in JavaScript:  Constructors  Object Methods Public Private Privileged OBJECTORIENTED PROGRAMMING Thursday, March 18, 2010
  13. 13. METHODS Thursday, March 18, 2010
  14. 14. Public Methods 14  One way to create a public method—a function that can be freely reference by code outside your object— is to attach it to the object’s prototype.  An object’s prototype is a special property that acts as a base reference of your object.  This prototype object is copied and applied to all new instances of your object. CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  15. 15. PROTOTYPE… Thursday, March 18, 2010
  16. 16. Public methods 16 var Person = function(name) { this.name = name; }; Person.prototype.say = function(){ return this.name; }; var rody = new Person(“Rody”) rody.say() var kris = new Person(“Kris”) kris.say() CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  17. 17. Prototype 17  Each function object has a property called prototype, which itself is an object and is initialized when function object is created  Can be removed, replaced, modified dynamically at runtime if internally allowed  Prototype is used to carry the shared state (data, method, etc.) among objects and also plays a role in inheritance of JavaScript  Reference: http://en.wikipedia.org/wiki/Prototype_pattern CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  18. 18. Prototype usage 18  say() is a property of the prototype object  but it behaves as if it's a property of the dude object  can we tell the difference? CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  19. 19. Own properties vs. prototype’s 19 >>> dude.hasOwnProperty('name'); true >>> dude.hasOwnProperty('say'); false CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  20. 20. Private Methods 20  Private methods are functions that are only accessible to methods inside your object and cannot be accessed by external code. CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  21. 21. Private Methods 21 var User = function (name) {   this.name = name;   function welcome () {     alert( “Welcome back, ” + name + “.”);   }   welcome(); } var me = new User( “Bob” );   me.welcome(); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  22. 22. “Privileged” Methods 22  The term privileged method was coined by Douglas Crockford. It is not a formal construct, but rather a technique.  Privileged methods essentially have one foot in the door: Then can access private methods and values within the object They are also publicly accessible CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  23. 23. “Privileged” Methods 23 var User = function (name, age) {   var year = (new Date()).getFullYear()                 – age;   this.getYearBorn = function () {     return year;   }; }; var me = new User( “Bob”, 28 ); alert(me.getYearBorn()); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  24. 24. CONSTRUCTORS Thursday, March 18, 2010
  25. 25. Constructor functions 25 var Person = function(name) { this.name = name; this.getName = function() { return this.name; }; }; var rody = new Person(“Rody”); alert(rody.getName()) CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  26. 26. A naming convention 26  MyConstructor  myFunction CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  27. 27. INHERITANCE Thursday, March 18, 2010
  28. 28. Parent constructor 28 function NormalObject() { this.name = 'normal'; this.getName = function() { return this.name; }; } CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  29. 29. Child constructor 29 function PreciousObject(){ this.shiny = true; this.round = true; } CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  30. 30. The inheritance 30 PreciousObject.prototype = new NormalObject(); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  31. 31. A child object 31 var crystal_ball = new PreciousObject(); crystal_ball.name = 'Crystal'; crystal_ball.round; // true crystal_ball.getName(); // "Crystal" CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  32. 32. Calling the superclass’ constructor 32 CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  33. 33. INHERITANCE BY COPYING Thursday, March 18, 2010
  34. 34. Two objects 34 var shiny = { shiny: true, round: true }; var normal = { name: 'name me', getName: function() { return this.name; } }; CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  35. 35. extend() 35 function extend(parent, child) { for (var i in parent) { child[i] = parent[i]; } } CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  36. 36. Inheritance 36 extend(normal, shiny); shiny.getName(); // "name me" CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  37. 37. Grand Finale 37  Using Scope, Closures, Contexts, and what we’ve discussed about OOP, we can dynamically generate classes based on information supplied to the constructor. CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  38. 38. Grand Finale 38 function User (properties) {   for ( var i in properties ) { function () {     this[“get” + i] = function () {        return properties[i];     };     this[“set” + i] = function (val) {        properties[i] = val;     };   })(); }} var me = new User( {   name: “Bob”,   age: 28 }); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  39. 39. Grand Finale 39 // …continued alert( me.name == null ); alert( me.getname() == “Bob” ); me.setage(21); alert( me.getage() == 21 ); CRIA-WT - Rody Middelkoop Thursday, March 18, 2010
  40. 40. References and a big thank you 40  Pro JavaScript Techniques, by John Resig  Douglas Crockford’s YUI Theater Presentations http://developer.yahoo.com/yui/theater  Beginning Object Oriented JavaScript, Stoyan Stefanov, http://www.slideshare.net/stoyan/beginning- objectoriented-javascript-presentation  Advanced Object-Oriented JavaScript, Ecker, http:// www.slideshare.net/ecker/advanced-objectoriented- javascript CRIA-WT - Rody Middelkoop Thursday, March 18, 2010

×