SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Lecture Outline

 Object-Oriented JavaScript

 Inheritance
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).
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

Weitere ähnliche Inhalte

Was ist angesagt?

New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

Was ist angesagt? (20)

Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Class method
Class methodClass method
Class method
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185The Ring programming language version 1.5.4 book - Part 38 of 185
The Ring programming language version 1.5.4 book - Part 38 of 185
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
OO in JavaScript
OO in JavaScriptOO in JavaScript
OO in JavaScript
 
C questions
C questionsC questions
C questions
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84The Ring programming language version 1.2 book - Part 27 of 84
The Ring programming language version 1.2 book - Part 27 of 84
 
iOS Session-2
iOS Session-2iOS Session-2
iOS Session-2
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 
OOPS
OOPSOOPS
OOPS
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
38 object-concepts (1)
38 object-concepts (1)38 object-concepts (1)
38 object-concepts (1)
 

Ähnlich wie Object Oriented JavaScript

Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Miao Siyu
 
Java script object model
Java script object modelJava script object model
Java script object model
James Hsieh
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
AntoJoseph36
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
Kris Kowal
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 

Ähnlich wie Object Oriented JavaScript (20)

Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Ian 20150116 java script oop
Ian 20150116 java script oopIan 20150116 java script oop
Ian 20150116 java script oop
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Js objects
Js objectsJs objects
Js objects
 
Say It With Javascript
Say It With JavascriptSay It With Javascript
Say It With Javascript
 
Defining method in JavaScript object.pptx
Defining method in JavaScript object.pptxDefining method in JavaScript object.pptx
Defining method in JavaScript object.pptx
 
Java script object model
Java script object modelJava script object model
Java script object model
 
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.pptDESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
DESIGNING A PERSISTENCE FRAMEWORK WITH PATTERNS.ppt
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Object-Oriented JavaScript
Object-Oriented JavaScriptObject-Oriented JavaScript
Object-Oriented JavaScript
 
Object-Oriented Javascript
Object-Oriented JavascriptObject-Oriented Javascript
Object-Oriented Javascript
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Javascript tid-bits
Javascript tid-bitsJavascript tid-bits
Javascript tid-bits
 
Bindings: the zen of montage
Bindings: the zen of montageBindings: the zen of montage
Bindings: the zen of montage
 
OBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .pptOBJECTS IN Object Oriented Programming .ppt
OBJECTS IN Object Oriented Programming .ppt
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 

Mehr von Julie Iskander

Mehr von Julie Iskander (20)

HTML 5
HTML 5HTML 5
HTML 5
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
C for Engineers
C for EngineersC for Engineers
C for Engineers
 
Design Pattern lecture 3
Design Pattern lecture 3Design Pattern lecture 3
Design Pattern lecture 3
 
Scriptaculous
ScriptaculousScriptaculous
Scriptaculous
 
Design Pattern lecture 4
Design Pattern lecture 4Design Pattern lecture 4
Design Pattern lecture 4
 
Design Pattern lecture 2
Design Pattern lecture 2Design Pattern lecture 2
Design Pattern lecture 2
 
Design Pattern lecture 1
Design Pattern lecture 1Design Pattern lecture 1
Design Pattern lecture 1
 
Ajax and ASP.NET AJAX
Ajax and ASP.NET AJAXAjax and ASP.NET AJAX
Ajax and ASP.NET AJAX
 
jQuery
jQueryjQuery
jQuery
 
ASP.NET Lecture 5
ASP.NET Lecture 5ASP.NET Lecture 5
ASP.NET Lecture 5
 
ASP.NET lecture 8
ASP.NET lecture 8ASP.NET lecture 8
ASP.NET lecture 8
 
ASP.NET Lecture 7
ASP.NET Lecture 7ASP.NET Lecture 7
ASP.NET Lecture 7
 
ASP.NET Lecture 6
ASP.NET Lecture 6ASP.NET Lecture 6
ASP.NET Lecture 6
 
ASP.NET Lecture 4
ASP.NET Lecture 4ASP.NET Lecture 4
ASP.NET Lecture 4
 
ASP.NET Lecture 3
ASP.NET Lecture 3ASP.NET Lecture 3
ASP.NET Lecture 3
 
ASP.NET Lecture 2
ASP.NET Lecture 2ASP.NET Lecture 2
ASP.NET Lecture 2
 
ASP.NET Lecture 1
ASP.NET Lecture 1ASP.NET Lecture 1
ASP.NET Lecture 1
 
AJAX and JSON
AJAX and JSONAJAX and JSON
AJAX and JSON
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Object Oriented JavaScript

  • 1.
  • 2. Lecture Outline  Object-Oriented JavaScript  Inheritance
  • 3.
  • 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).
  • 20.
  • 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

Hinweis der Redaktion

  1. 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.
  2. 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;
  3. var a = [&apos;red&apos;, &apos;green&apos;, &apos;blue&apos;];a.inArray(&apos;red&apos;);truea.inArray(&apos;yellow&apos;);false
  4. 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.
  5. isPrototypeOf() to check whether an object inherits another or no