SlideShare a Scribd company logo
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
Phúc Đỗ
 
PPT
Advanced Javascript
Manikanda kumar
 
PDF
Core concepts-javascript
Prajwala Manchikatla
 
PPTX
Advanced JavaScript
Nascenia IT
 
PPTX
Stamps - a better way to object composition
Vasyl Boroviak
 
PPT
Advanced Javascript
Adieu
 
PDF
Uncommon Design Patterns
Stefano Fago
 
PPTX
Oojs 1.1
Rodica Dada
 
11. session 11 functions and objects
Phúc Đỗ
 
Advanced Javascript
Manikanda kumar
 
Core concepts-javascript
Prajwala Manchikatla
 
Advanced JavaScript
Nascenia IT
 
Stamps - a better way to object composition
Vasyl Boroviak
 
Advanced Javascript
Adieu
 
Uncommon Design Patterns
Stefano Fago
 
Oojs 1.1
Rodica Dada
 

What's hot (20)

PDF
Csharp_Chap03
Mohamed Krar
 
PDF
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
PPTX
Introduction to Client-Side Javascript
Julie Iskander
 
PPT
Advanced JavaScript
Fu Cheng
 
PPS
Class method
kamal kotecha
 
PPTX
classes & objects in cpp overview
gourav kottawar
 
PPT
data Structure Lecture 1
Teksify
 
PDF
The Ring programming language version 1.5.4 book - Part 38 of 185
Mahmoud Samir Fayed
 
PDF
Advanced javascript
Doeun KOCH
 
DOCX
New microsoft office word document (2)
rashmita_mishra
 
PDF
Java Script Best Practices
Enrique Juan de Dios
 
PPTX
OO in JavaScript
Gunjan Kumar
 
DOCX
C questions
parm112
 
PPTX
Prototype Framework
Julie Iskander
 
PDF
The Ring programming language version 1.2 book - Part 27 of 84
Mahmoud Samir Fayed
 
PPTX
iOS Session-2
Hussain Behestee
 
PPTX
Ajaxworld
deannalagason
 
PDF
FP in Java - Project Lambda and beyond
Mario Fusco
 
PPT
38 object-concepts (1)
Shambhavi Vats
 
Csharp_Chap03
Mohamed Krar
 
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Introduction to Client-Side Javascript
Julie Iskander
 
Advanced JavaScript
Fu Cheng
 
Class method
kamal kotecha
 
classes & objects in cpp overview
gourav kottawar
 
data Structure Lecture 1
Teksify
 
The Ring programming language version 1.5.4 book - Part 38 of 185
Mahmoud Samir Fayed
 
Advanced javascript
Doeun KOCH
 
New microsoft office word document (2)
rashmita_mishra
 
Java Script Best Practices
Enrique Juan de Dios
 
OO in JavaScript
Gunjan Kumar
 
C questions
parm112
 
Prototype Framework
Julie Iskander
 
The Ring programming language version 1.2 book - Part 27 of 84
Mahmoud Samir Fayed
 
iOS Session-2
Hussain Behestee
 
Ajaxworld
deannalagason
 
FP in Java - Project Lambda and beyond
Mario Fusco
 
38 object-concepts (1)
Shambhavi Vats
 
Ad

Similar to Object Oriented JavaScript (20)

PPT
Advanced Javascript
relay12
 
PPTX
Ian 20150116 java script oop
LearningTech
 
PPT
25-functions.ppt
JyothiAmpally
 
PDF
Javascript Design Patterns
Subramanyan Murali
 
PPTX
Advanced JavaScript
Zsolt Mészárovics
 
PPTX
Design patterns in javascript
Miao Siyu
 
PPT
Object Oriented JavaScript
Donald Sipe
 
PPTX
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
PDF
Js objects
anubavam-techkt
 
PDF
Say It With Javascript
Giovanni Scerra ☃
 
PPTX
Defining method in JavaScript object.pptx
Steins18
 
PDF
Java script object model
James Hsieh
 
PPT
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 
PDF
TypeScript Introduction
Dmitry Sheiko
 
KEY
Object-Oriented JavaScript
kvangork
 
KEY
Object-Oriented Javascript
kvangork
 
PPTX
Functions and Objects in JavaScript
Dhananjay Kumar
 
KEY
Javascript tid-bits
David Atchley
 
PDF
Bindings: the zen of montage
Kris Kowal
 
PPT
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
Advanced Javascript
relay12
 
Ian 20150116 java script oop
LearningTech
 
25-functions.ppt
JyothiAmpally
 
Javascript Design Patterns
Subramanyan Murali
 
Advanced JavaScript
Zsolt Mészárovics
 
Design patterns in javascript
Miao Siyu
 
Object Oriented JavaScript
Donald Sipe
 
Object Oriented Programming using C++: Ch11 Virtual Functions.pptx
RashidFaridChishti
 
Js objects
anubavam-techkt
 
Say It With Javascript
Giovanni Scerra ☃
 
Defining method in JavaScript object.pptx
Steins18
 
Java script object model
James Hsieh
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 
TypeScript Introduction
Dmitry Sheiko
 
Object-Oriented JavaScript
kvangork
 
Object-Oriented Javascript
kvangork
 
Functions and Objects in JavaScript
Dhananjay Kumar
 
Javascript tid-bits
David Atchley
 
Bindings: the zen of montage
Kris Kowal
 
OBJECTS IN Object Oriented Programming .ppt
SaadAsim11
 
Ad

More from Julie Iskander (20)

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

Recently uploaded (20)

PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PPT
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Coupa-Kickoff-Meeting-Template presentai
annapureddyn
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
This slide provides an overview Technology
mineshkharadi333
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 

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