Object Oriented JavaScript
Lecture Outline

 Object-Oriented JavaScript

 Inheritance
Object Oriented JavaScript
Objects

 Is a self-contained collection of data.

 The data can be
    properties, a variable belonging to an object.
    methods, a function that the object can invoke, an
     object in itself.

 Properties and methods are both accessed using
  dot notation.
Objects (Cont’d)

 No class, classless approach

 Objects are created through:
    Literal notation using { }
    Constructors function
Using object literal
              notation{}
 To create an empty object
    var x={}

 To create an object with properties and methods
       var student={
         track:"PD",
         marks:[100,200,300],
         getTotal: function ()
         {
            var sum=0;
            for(var i in this.marks)
               sum+=this.marks[i];
            return sum;
         }
       }
Accessing Properties

 Using square bracket notation
   student[„track‟] PD

 Using the dot notation,
   student.track  PD
Objects inside Objects

 Example
       var book = {
            name: 'Catch-22',
            published: 1961,
            author: {
                 firstname: 'Joseph',
                 lastname: 'Heller'
            }
       };

 book.author.firstname
 book['author']['lastname']
Delete a Property

delete student.track;
Using Constructor function

 function student(name) {
       this.track="PD”;
       this.name=name;
       this.marks=[100,200,300];
       this.getTotal= function ()
           {
                var sum=0;
                for(var i in this.marks)
                   sum+=this.marks[i];
                return sum;
           };
       }

 To create an object, use new operator
       var std = new student(“Smith”);
What happens when you
  create an object without
      ‘new’ operator?
 var std =student()

 this  refers to global object ‘window’

 std  undefined or whatever constructor returns if it
           returns anything
Try Objects
Use Developer tools
constructor Property

 It contains a reference to the constructor function used to
  create this object.
   std.constructor  student(name)
    var h3 = new std.constructor('Rafaello');

 If an object was created using the object literal notation??
    its constructor is the built-in Object() constructor function.
    var o = {};
    o.constructor Object()  empty object
    typeof o.constructor  "function"
Passing Objects

 When you copy an object or pass it to a function, you
  only pass a reference to that object. Consequently, if you
  make a change to the reference, you are actually
  modifying the original object.
 Example
      var original = {howmany: 1};
      var copy = original;
      copy.howmany  1
      copy.howmany = 100;
       original.howmany  100

 The same thing applies when passing objects to
  functions:
Comparing Objects

 true  iff you compare two references to the
  same object. >>>
    var fido = {breed: 'dog'};
    var benji = {breed: 'dog'};
    benji == fido  false

 However
    var mydog = benji;
    mydog == benji  true
Object object

 Object is the parent of all JavaScript objects

 Every object created inherits from it.

 To create a new empty object
       var o = {};
       var o = new Object();

 Properties:
       o.constructor property returns the constructor function
       o.toString() is a method that returns a string representation of the
        object
       o.valueOf() returns a single-value representation of the object, often
        this is the object itself
Private Members

 Ordinary ’var’ of the constructor are private members.
    function Container(param)
    {
        this.member = param;
        var secret = 3;
        var that = this;
    }

 secret and that are attached to the object, but they are
  not accessible to the outside, nor are they accessible to
  the object's own public methods. They are accessible to
  private methods.
Private Methods
function Container(param)
{
     function dec()
    {
        if (secret > 0)
        {
             secret -= 1; return true;
         }
        else
        {return false;}
    }
this.member = param; var secret = 3;     var that =
this;
}
Privileged Method

 Is able to access the private variables and
  methods, and is itself public.
   this.service = function ()
   {
        return dec() ? that.member : null;
   };

 Private and privileged members can only be made
  when an object is constructed (in a constructor).
Object Oriented JavaScript
Inheritance

 Used for code reuse

 JavaScript don’t use class-inheritance but prototype-
  inheritance (based on Objects)

 There are many ways to implement inheritance.

 We will cover Prototype Chaining
Function Object

 Properties:
    length: number of arguments
    constructor: Function()
    prototype: initially is an empty object
Prototype

 JavaScript prototype-based object model

 Every function object has a prototype property,

 Initially empty Object

 Augment this empty object with properties and
  methods.

 Only be used when function is used as a
  constructor.
Adding Methods and
               Properties
function                            Gadget.prototype.price = 100;
Gadget(name, color) {
    this.name = name;
                                    Gadget.prototype.rating = 3;
    this.color = color;             Gadget.prototype.getInfo =
    this.whatAreYou =               function() {
    function()                           return 'Rating: ' + this.rating +
    {                                    ', price: ' + this.price;
    return 'I am a ' + this.color
    + ' ' + this.name;              };
    }

}
What if object contain a
    property defined in
         prototype?
 Own Property overrides prototype property

 propertyIsEnumerable()

 hasOwnProperty()

 isPrototypeOf()
What is the result?

function Gadget(name, color)    var newtoy = new
                                Gadget('webcam', 'black');
{                                   for (var prop in newtoy)
    this.name = name;
                                    {
    this.color = color;
                                    console.log(prop + ' = ' +
    this.someMethod =
    function(){return 1;}           newtoy[prop]);
                                    }
}
                                name = webcam
Gadget.prototype.price = 100;   color = black
                                someMethod = function () { return 1; }
Gadget.prototype.rating = 3;    price = 100
                                rating = 3
What is the result?

function                       var newtoy = new
Gadget(name, color)            Gadget('webcam', 'black');
{                              for (var prop in newtoy) {
    this.name = name;              if (newtoy.hasOwnProperty(prop))
    this.color = color;             {
    this.someMethod =                   console.log(prop + '=' +
    function(){return 1;}          newtoy[prop]);
}                                  }
                               }
Gadget.prototype.price =
100;                           name = webcam
Gadget.prototype.rating = 3;   color = black
                               someMethod = function () { return 1; }
Augmenting Built-in
              Objects

Array.prototype.inArray = function(needle) {
    for (var i = 0, len = this.length; i < len; i++) {
       if (this[i] === needle) {
               return true;
       }
    }
    return false;

}
Prototype Chaining
function Shape(){
    this.name = 'shape';
    this.toString = function()
    {return this.name;};
}
function TwoDShape(){
                                    Inheritance is done through:
        this.name = '2D
shape';                                TwoDShape.prototype
}                                      = new Shape();
function                               Triangle.prototype =
Triangle(side, height) {               new TwoDShape();
    this.name = 'Triangle';
    this.side = side;
    this.height = height;
    this.getArea =
    function(){return this.side *
    this.height / 2;};
}
Note

 When you completely overwrite the
  prototype,
   Has negative side effects on the constructor
    property.
   Solution:
     TwoDShape.prototype.constructor =
       TwoDShape;
     Triangle.prototype.constructor = Triangle;
What do the JavaScript
engine does when you call
      my.toString()?
 var my=new Triangle(5,10)
    Loops through all of the properties of my
    If not found, looks at the object that my.__proto__
     points to; the instance of TwoDShape() .
    Loops through the instance of TwoDShape.
    If not found, checks the __proto__ of that object that
     points to the instance of Shape().
    Loops through the instance of Shape() and toString()
     is finally found!
For efficiency:
  Moving shared properties to the
  prototype
function Shape(){}                      function Triangle(side, height) {
Shape.prototype.name = 'shape';         this.side = side;
Shape.prototype.toString = function()   this.height = height;
{return this.name;};                    }

function TwoDShape(){}                  Triangle.prototype = new
TwoDShape.prototype = new               TwoDShape();
Shape();                                Triangle.prototype.constructor =
TwoDShape.prototype.constructor =       Triangle;
TwoDShape;
TwoDShape.prototype.name = '2D          Triangle.prototype.name = 'Triangle';
shape';                                 Triangle.prototype.getArea =
                                        function(){return this.side *
                                        this.height / 2;};
References
 Object-Oriented JavaScript Create Scalable, reusable, high
  quality JavaScript applications and libraries, Stoyan
  Stefanov, 2008.

 http://www.quirksmode.org/js

More Related Content

PPTX
11. session 11 functions and objects
PPT
Advanced Javascript
PDF
Core concepts-javascript
PPTX
Advanced JavaScript
PPTX
Stamps - a better way to object composition
PPT
Advanced Javascript
PDF
Uncommon Design Patterns
PPTX
Oojs 1.1
11. session 11 functions and objects
Advanced Javascript
Core concepts-javascript
Advanced JavaScript
Stamps - a better way to object composition
Advanced Javascript
Uncommon Design Patterns
Oojs 1.1

What's hot (20)

PDF
Csharp_Chap03
PDF
Powerful JavaScript Tips and Best Practices
PPTX
Introduction to Client-Side Javascript
PPT
Advanced JavaScript
PPS
Class method
PPTX
classes & objects in cpp overview
PPT
data Structure Lecture 1
PDF
The Ring programming language version 1.5.4 book - Part 38 of 185
PDF
Advanced javascript
DOCX
New microsoft office word document (2)
PDF
Java Script Best Practices
PPTX
OO in JavaScript
DOCX
C questions
PPTX
Prototype Framework
PDF
The Ring programming language version 1.2 book - Part 27 of 84
PPTX
iOS Session-2
PPTX
Ajaxworld
PDF
FP in Java - Project Lambda and beyond
PPT
38 object-concepts (1)
Csharp_Chap03
Powerful JavaScript Tips and Best Practices
Introduction to Client-Side Javascript
Advanced JavaScript
Class method
classes & objects in cpp overview
data Structure Lecture 1
The Ring programming language version 1.5.4 book - Part 38 of 185
Advanced javascript
New microsoft office word document (2)
Java Script Best Practices
OO in JavaScript
C questions
Prototype Framework
The Ring programming language version 1.2 book - Part 27 of 84
iOS Session-2
Ajaxworld
FP in Java - Project Lambda and beyond
38 object-concepts (1)

Similar to Object Oriented JavaScript (20)

PPT
Beginning Object-Oriented JavaScript
PDF
Js objects
PPT
Advanced Javascript
PDF
Prototype
PPT
Advanced JavaScript
PPTX
Typescript barcelona
KEY
Javascript tid-bits
PDF
JavaScript Essentials
PPTX
WEB222-lecture-4.pptx
PPT
JavaScript In Object Oriented Way
PDF
Professional JavaScript Development - Creating Reusable Code
PDF
The many facets of code reuse in JavaScript
PPTX
Advanced JavaScript
PPTX
JavsScript OOP
PPTX
Javascript Objects Deep Dive
PPTX
Ian 20150116 java script oop
PDF
JavaScript Inheritance
PPT
JavaScript - Programming Languages course
PDF
JS Level Up: Prototypes
Beginning Object-Oriented JavaScript
Js objects
Advanced Javascript
Prototype
Advanced JavaScript
Typescript barcelona
Javascript tid-bits
JavaScript Essentials
WEB222-lecture-4.pptx
JavaScript In Object Oriented Way
Professional JavaScript Development - Creating Reusable Code
The many facets of code reuse in JavaScript
Advanced JavaScript
JavsScript OOP
Javascript Objects Deep Dive
Ian 20150116 java script oop
JavaScript Inheritance
JavaScript - Programming Languages course
JS Level Up: Prototypes

More from Julie Iskander (20)

PPTX
PPTX
Data structures and algorithms
PPTX
C for Engineers
PPTX
Design Pattern lecture 3
PPTX
Scriptaculous
PPTX
Design Pattern lecture 4
PPTX
Design Pattern lecture 2
PPTX
Design Pattern lecture 1
PPTX
Ajax and ASP.NET AJAX
PPTX
PPTX
ASP.NET Lecture 5
PPTX
ASP.NET lecture 8
PPTX
ASP.NET Lecture 7
PPTX
ASP.NET Lecture 6
PPTX
ASP.NET Lecture 4
PPTX
ASP.NET Lecture 3
PPTX
ASP.NET Lecture 2
PPTX
ASP.NET Lecture 1
PPTX
AJAX and JSON
PPTX
DOM and Events
Data structures and algorithms
C for Engineers
Design Pattern lecture 3
Scriptaculous
Design Pattern lecture 4
Design Pattern lecture 2
Design Pattern lecture 1
Ajax and ASP.NET AJAX
ASP.NET Lecture 5
ASP.NET lecture 8
ASP.NET Lecture 7
ASP.NET Lecture 6
ASP.NET Lecture 4
ASP.NET Lecture 3
ASP.NET Lecture 2
ASP.NET Lecture 1
AJAX and JSON
DOM and Events

Recently uploaded (20)

PDF
Identification of potential depression in social media posts
PPTX
Presentation - Principles of Instructional Design.pptx
PDF
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf
PDF
NewMind AI Journal Monthly Chronicles - August 2025
PPTX
Information-Technology-in-Human-Society.pptx
PDF
Advancing precision in air quality forecasting through machine learning integ...
PDF
giants, standing on the shoulders of - by Daniel Stenberg
PDF
Launch a Bumble-Style App with AI Features in 2025.pdf
PDF
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
PDF
Connector Corner: Transform Unstructured Documents with Agentic Automation
PDF
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
PDF
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
PDF
Early detection and classification of bone marrow changes in lumbar vertebrae...
PDF
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
PPTX
How to Convert Tickets Into Sales Opportunity in Odoo 18
PDF
Build Real-Time ML Apps with Python, Feast & NoSQL
PDF
Streamline Vulnerability Management From Minimal Images to SBOMs
PDF
Rapid Prototyping: A lecture on prototyping techniques for interface design
PPTX
How to use fields_get method in Odoo 18
PDF
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf
Identification of potential depression in social media posts
Presentation - Principles of Instructional Design.pptx
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf
NewMind AI Journal Monthly Chronicles - August 2025
Information-Technology-in-Human-Society.pptx
Advancing precision in air quality forecasting through machine learning integ...
giants, standing on the shoulders of - by Daniel Stenberg
Launch a Bumble-Style App with AI Features in 2025.pdf
Transform-Your-Supply-Chain-with-AI-Driven-Quality-Engineering.pdf
Connector Corner: Transform Unstructured Documents with Agentic Automation
CXOs-Are-you-still-doing-manual-DevOps-in-the-age-of-AI.pdf
ment.tech-Siri Delay Opens AI Startup Opportunity in 2025.pdf
Early detection and classification of bone marrow changes in lumbar vertebrae...
Transform-Quality-Engineering-with-AI-A-60-Day-Blueprint-for-Digital-Success.pdf
How to Convert Tickets Into Sales Opportunity in Odoo 18
Build Real-Time ML Apps with Python, Feast & NoSQL
Streamline Vulnerability Management From Minimal Images to SBOMs
Rapid Prototyping: A lecture on prototyping techniques for interface design
How to use fields_get method in Odoo 18
CCUS-as-the-Missing-Link-to-Net-Zero_AksCurious.pdf

Object Oriented JavaScript

  • 2. Lecture Outline  Object-Oriented JavaScript  Inheritance
  • 4. Objects  Is a self-contained collection of data.  The data can be  properties, a variable belonging to an object.  methods, a function that the object can invoke, an object in itself.  Properties and methods are both accessed using dot notation.
  • 5. Objects (Cont’d)  No class, classless approach  Objects are created through:  Literal notation using { }  Constructors function
  • 6. Using object literal notation{}  To create an empty object  var x={}  To create an object with properties and methods var student={ track:"PD", marks:[100,200,300], getTotal: function () { var sum=0; for(var i in this.marks) sum+=this.marks[i]; return sum; } }
  • 7. Accessing Properties  Using square bracket notation  student[„track‟] PD  Using the dot notation,  student.track  PD
  • 8. Objects inside Objects  Example var book = { name: 'Catch-22', published: 1961, author: { firstname: 'Joseph', lastname: 'Heller' } };  book.author.firstname  book['author']['lastname']
  • 10. Using Constructor function  function student(name) { this.track="PD”; this.name=name; this.marks=[100,200,300]; this.getTotal= function () { var sum=0; for(var i in this.marks) sum+=this.marks[i]; return sum; }; }  To create an object, use new operator  var std = new student(“Smith”);
  • 11. What happens when you create an object without ‘new’ operator?  var std =student()  this  refers to global object ‘window’  std  undefined or whatever constructor returns if it returns anything
  • 13. constructor Property  It contains a reference to the constructor function used to create this object.  std.constructor  student(name)  var h3 = new std.constructor('Rafaello');  If an object was created using the object literal notation??  its constructor is the built-in Object() constructor function.  var o = {};  o.constructor Object()  empty object  typeof o.constructor  "function"
  • 14. Passing Objects  When you copy an object or pass it to a function, you only pass a reference to that object. Consequently, if you make a change to the reference, you are actually modifying the original object.  Example  var original = {howmany: 1};  var copy = original;  copy.howmany  1  copy.howmany = 100;  original.howmany  100  The same thing applies when passing objects to functions:
  • 15. Comparing Objects  true  iff you compare two references to the same object. >>>  var fido = {breed: 'dog'};  var benji = {breed: 'dog'};  benji == fido  false  However  var mydog = benji;  mydog == benji  true
  • 16. Object object  Object is the parent of all JavaScript objects  Every object created inherits from it.  To create a new empty object  var o = {};  var o = new Object();  Properties:  o.constructor property returns the constructor function  o.toString() is a method that returns a string representation of the object  o.valueOf() returns a single-value representation of the object, often this is the object itself
  • 17. Private Members  Ordinary ’var’ of the constructor are private members.  function Container(param)  {  this.member = param;  var secret = 3;  var that = this;  }  secret and that are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods.
  • 18. Private Methods function Container(param) { function dec() { if (secret > 0) { secret -= 1; return true; } else {return false;} } this.member = param; var secret = 3; var that = this; }
  • 19. Privileged Method  Is able to access the private variables and methods, and is itself public. this.service = function () { return dec() ? that.member : null; };  Private and privileged members can only be made when an object is constructed (in a constructor).
  • 21. Inheritance  Used for code reuse  JavaScript don’t use class-inheritance but prototype- inheritance (based on Objects)  There are many ways to implement inheritance.  We will cover Prototype Chaining
  • 22. Function Object  Properties:  length: number of arguments  constructor: Function()  prototype: initially is an empty object
  • 23. Prototype  JavaScript prototype-based object model  Every function object has a prototype property,  Initially empty Object  Augment this empty object with properties and methods.  Only be used when function is used as a constructor.
  • 24. Adding Methods and Properties function Gadget.prototype.price = 100; Gadget(name, color) { this.name = name; Gadget.prototype.rating = 3; this.color = color; Gadget.prototype.getInfo = this.whatAreYou = function() { function() return 'Rating: ' + this.rating + { ', price: ' + this.price; return 'I am a ' + this.color + ' ' + this.name; }; } }
  • 25. What if object contain a property defined in prototype?  Own Property overrides prototype property  propertyIsEnumerable()  hasOwnProperty()  isPrototypeOf()
  • 26. What is the result? function Gadget(name, color) var newtoy = new Gadget('webcam', 'black'); { for (var prop in newtoy) this.name = name; { this.color = color; console.log(prop + ' = ' + this.someMethod = function(){return 1;} newtoy[prop]); } } name = webcam Gadget.prototype.price = 100; color = black someMethod = function () { return 1; } Gadget.prototype.rating = 3; price = 100 rating = 3
  • 27. What is the result? function var newtoy = new Gadget(name, color) Gadget('webcam', 'black'); { for (var prop in newtoy) { this.name = name; if (newtoy.hasOwnProperty(prop)) this.color = color; { this.someMethod = console.log(prop + '=' + function(){return 1;} newtoy[prop]); } } } Gadget.prototype.price = 100; name = webcam Gadget.prototype.rating = 3; color = black someMethod = function () { return 1; }
  • 28. Augmenting Built-in Objects Array.prototype.inArray = function(needle) { for (var i = 0, len = this.length; i < len; i++) { if (this[i] === needle) { return true; } } return false; }
  • 30. function Shape(){ this.name = 'shape'; this.toString = function() {return this.name;}; } function TwoDShape(){ Inheritance is done through: this.name = '2D shape'; TwoDShape.prototype } = new Shape(); function Triangle.prototype = Triangle(side, height) { new TwoDShape(); this.name = 'Triangle'; this.side = side; this.height = height; this.getArea = function(){return this.side * this.height / 2;}; }
  • 31. Note  When you completely overwrite the prototype,  Has negative side effects on the constructor property.  Solution:  TwoDShape.prototype.constructor = TwoDShape;  Triangle.prototype.constructor = Triangle;
  • 32. What do the JavaScript engine does when you call my.toString()?  var my=new Triangle(5,10)  Loops through all of the properties of my  If not found, looks at the object that my.__proto__ points to; the instance of TwoDShape() .  Loops through the instance of TwoDShape.  If not found, checks the __proto__ of that object that points to the instance of Shape().  Loops through the instance of Shape() and toString() is finally found!
  • 33. For efficiency: Moving shared properties to the prototype function Shape(){} function Triangle(side, height) { Shape.prototype.name = 'shape'; this.side = side; Shape.prototype.toString = function() this.height = height; {return this.name;}; } function TwoDShape(){} Triangle.prototype = new TwoDShape.prototype = new TwoDShape(); Shape(); Triangle.prototype.constructor = TwoDShape.prototype.constructor = Triangle; TwoDShape; TwoDShape.prototype.name = '2D Triangle.prototype.name = 'Triangle'; shape'; Triangle.prototype.getArea = function(){return this.side * this.height / 2;};
  • 34. References  Object-Oriented JavaScript Create Scalable, reusable, high quality JavaScript applications and libraries, Stoyan Stefanov, 2008.  http://www.quirksmode.org/js

Editor's Notes

  • #19: By convention, we make a private ‘that’ variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification, which causes this to be set incorrectly for inner functions (private methods).Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.
  • #25: var newtoy = new Gadget(&apos;webcam&apos;, &apos;black&apos;);newtoy.name;&quot;webcam&quot;newtoy.color;&quot;black&quot;newtoy.whatAreYou();&quot;I am a black webcam&quot;newtoy.price;100newtoy.rating;3newtoy.getInfo();&quot;Rating: 3, price: 100&quot;
  • #29: var a = [&apos;red&apos;, &apos;green&apos;, &apos;blue&apos;];a.inArray(&apos;red&apos;);truea.inArray(&apos;yellow&apos;);false
  • #30: Instead of augmenting an object with individual properties or methods we can specify another object as the prototype object. Thus, making an object inherit all properties of another object.
  • #34: isPrototypeOf() to check whether an object inherits another or no