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.    m...
Objects (Cont’d) No class, classless approach Objects are created through:    Literal notation using { }    Constructo...
Using object literal              notation{} To create an empty object    var x={} To create an object with properties ...
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,            autho...
Delete a Propertydelete student.track;
Using Constructor function function student(name) {       this.track="PD”;       this.name=name;       this.marks=[100,20...
What happens when you  create an object without      ‘new’ operator? var std =student() this  refers to global object ‘...
Try ObjectsUse Developer tools
constructor Property It contains a reference to the constructor function used to  create this object.   std.constructor ...
Passing Objects When you copy an object or pass it to a function, you  only pass a reference to that object. Consequently...
Comparing Objects true  iff you compare two references to the  same object. >>>    var fido = {breed: dog};    var ben...
Object object Object is the parent of all JavaScript objects Every object created inherits from it. To create a new emp...
Private Members Ordinary ’var’ of the constructor are private members.    function Container(param)    {        this.m...
Private Methodsfunction Container(param){     function dec()    {        if (secret > 0)        {             secret -= 1;...
Privileged Method Is able to access the private variables and  methods, and is itself public.   this.service = function (...
Inheritance Used for code reuse JavaScript don’t use class-inheritance but prototype-  inheritance (based on Objects) T...
Function Object Properties:    length: number of arguments    constructor: Function()    prototype: initially is an em...
Prototype JavaScript prototype-based object model Every function object has a prototype property, Initially empty Objec...
Adding Methods and               Propertiesfunction                            Gadget.prototype.price = 100;Gadget(name, c...
What if object contain a    property defined in         prototype? Own Property overrides prototype property propertyIsE...
What is the result?function Gadget(name, color)    var newtoy = new                                Gadget(webcam, black);{...
What is the result?function                       var newtoy = newGadget(name, color)            Gadget(webcam, black);{  ...
Augmenting Built-in              ObjectsArray.prototype.inArray = function(needle) {    for (var i = 0, len = this.length;...
Prototype Chaining
function Shape(){    this.name = shape;    this.toString = function()    {return this.name;};}function TwoDShape(){       ...
Note When you completely overwrite the  prototype,   Has negative side effects on the constructor    property.   Soluti...
What do the JavaScriptengine does when you call      my.toString()? var my=new Triangle(5,10)    Loops through all of th...
For efficiency:  Moving shared properties to the  prototypefunction Shape(){}                      function Triangle(side,...
References Object-Oriented JavaScript Create Scalable, reusable, high  quality JavaScript applications and libraries, Sto...
Object Oriented JavaScript
Object Oriented JavaScript
Object Oriented JavaScript
Upcoming SlideShare
Loading in …5
×

Object Oriented JavaScript

1,081 views

Published on

Describing Object oriented aspects of JavaScript. Prototype Chaining Inheritance is described.

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

No Downloads
Views
Total views
1,081
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
1
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • 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.
  • var newtoy = new Gadget('webcam', 'black');newtoy.name;"webcam"newtoy.color;"black"newtoy.whatAreYou();"I am a black webcam"newtoy.price;100newtoy.rating;3newtoy.getInfo();"Rating: 3, price: 100"
  • var a = ['red', 'green', 'blue'];a.inArray('red');truea.inArray('yellow');false
  • 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.
  • isPrototypeOf() to check whether an object inherits another or no
  • Object Oriented JavaScript

    1. 1. Lecture Outline Object-Oriented JavaScript Inheritance
    2. 2. 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.
    3. 3. Objects (Cont’d) No class, classless approach Objects are created through:  Literal notation using { }  Constructors function
    4. 4. 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; } }
    5. 5. Accessing Properties Using square bracket notation  student[„track‟] PD Using the dot notation,  student.track  PD
    6. 6. Objects inside Objects Example var book = { name: Catch-22, published: 1961, author: { firstname: Joseph, lastname: Heller } }; book.author.firstname book[author][lastname]
    7. 7. Delete a Propertydelete student.track;
    8. 8. 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”);
    9. 9. 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
    10. 10. Try ObjectsUse Developer tools
    11. 11. 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"
    12. 12. 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:
    13. 13. 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
    14. 14. 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
    15. 15. 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 objects own public methods. They are accessible to private methods.
    16. 16. Private Methodsfunction Container(param){ function dec() { if (secret > 0) { secret -= 1; return true; } else {return false;} }this.member = param; var secret = 3; var that =this;}
    17. 17. 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).
    18. 18. 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
    19. 19. Function Object Properties:  length: number of arguments  constructor: Function()  prototype: initially is an empty object
    20. 20. 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.
    21. 21. Adding Methods and Propertiesfunction 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; }; }}
    22. 22. What if object contain a property defined in prototype? Own Property overrides prototype property propertyIsEnumerable() hasOwnProperty() isPrototypeOf()
    23. 23. 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 = webcamGadget.prototype.price = 100; color = black someMethod = function () { return 1; }Gadget.prototype.rating = 3; price = 100 rating = 3
    24. 24. What is the result?function var newtoy = newGadget(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 = webcamGadget.prototype.rating = 3; color = black someMethod = function () { return 1; }
    25. 25. Augmenting Built-in ObjectsArray.prototype.inArray = function(needle) { for (var i = 0, len = this.length; i < len; i++) { if (this[i] === needle) { return true; } } return false;}
    26. 26. Prototype Chaining
    27. 27. function Shape(){ this.name = shape; this.toString = function() {return this.name;};}function TwoDShape(){ Inheritance is done through: this.name = 2Dshape; 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;};}
    28. 28. Note When you completely overwrite the prototype,  Has negative side effects on the constructor property.  Solution:  TwoDShape.prototype.constructor = TwoDShape;  Triangle.prototype.constructor = Triangle;
    29. 29. What do the JavaScriptengine 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!
    30. 30. For efficiency: Moving shared properties to the prototypefunction 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 = newTwoDShape.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;};
    31. 31. References Object-Oriented JavaScript Create Scalable, reusable, high quality JavaScript applications and libraries, Stoyan Stefanov, 2008. http://www.quirksmode.org/js

    ×