SlideShare ist ein Scribd-Unternehmen logo
1 von 36
OO in JavaScript Gunjan Kumar
Agenda JavaScript you need to know OO in JavaScript  OO basics Inheritance Encapsulation Polymorphism Class Object and properties Object literals (JSON) Functions and function context, Anonymous functions Prototype and inheritance Closure unobtrusive JavaScript - the way our code should be structured
OO in JS Prototype-based programming is a style of object-oriented programming in which classes are not present behavior reuse (inheritance) is accomplished through a process of decorating existing objects which serve as prototypes.  This model is also known as class-less, prototype-oriented, or instance-based programming. Support in JS :  Inheritance - The ability to define the behavior of one object in terms of another by sub-classing.  Encapsulation - Support for method calls on a JavaScript object as a member of a Class Polymorphism - The ability for two classes to respond to the same (collection of) methods.
Inheritance Inheritance allows one class to replicate and extend the functionality of another without having to re-implement the existing class’s behavior JavaScript only supports single class inheritance Supported by prototype and other options in JS More details later in the slides
Encapsulation Encapsulation ensures that an object’s state can only be changed by the object itself, as a result of that object’s performing one of the operations (methods) it supports.  Supported by defining variables in function with this. And then defining  functions to access these variables       function A(){     var x = 7; this.GetX = function () { return x; } this.SetX = function (xT) { x = xT; }         } obj = new A;        obj2 = new A; document.write(obj.GetX() + ' ' + obj2.GetX()); obj.SetX(14); document.write(' ' + obj.GetX() + ' ' + obj2.GetX());         //alert(obj.x);//gives undefined
Abstraction Abstraction key concept that underpins the very notion of objects - that they abstract the details of their own implementation. This can be achieved by inheritance (specialization), or composition.  JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects
Polymorphism Polymorphism ability to appear in different forms.  allows an object of a given class to be treated as if it were an object of its superclass, despite the fact that one or more of the superclass’s methods may be defined differently (overridden) in the object’s true class. In JS, different classes can define methods with the same name; methods are scoped to the class in which they're defined. Achieved by simply having different object classes implement a collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.
Polymorphism function A()    {     this.x = 1;     }  A.prototype.DoIt = function()   // Define Method     {     this.x += 1;     }      function B()    {     this.x = 1;     }  B.prototype.DoIt = function()    // Define Method     {     this.x += 2;     }     a = new A;     b = new B; a.DoIt(); b.DoIt(); document.write(a.x + ', ' + b.x);
The Class JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java.  This is of relevance ONLY if we expect multiple objects with same properties – thus reducing the lines of code No formal way to define a class. Any function definition is a class Properties and methods can be defined within the function To instantiate, we use the new keyword We can define the function to accept parameters to simulate a constructor which sets default params
The Class function Owner(_name, _age) {             this.name = _name; this.age = _age;         } function Bike(_name, _model, _make, _mileage, _owner) {             this.name = _name; this.model = _model; this.make = _make; this.mileage = _mileage; this.owner = _owner; this.whatAmI = function () { return this.year + ' ' + this.make + ' ' + this.model; }         } var bike3 = new Bike('Yamaha3', 'Model 3', new Date(2008, 3, 12), 33, new Owner('owner 3', 33));
The Object Create object by new Object() No properties by default. Keep adding dynamically. primary purpose of an Object instance to serve as a container for a named collection of other objects The name of a property is a string Value can be any JavaScript object, be it a Number, String, Date, Array, basic Object, or any other JavaScript object type (including functions)
The Object You can also create instance of the Class function Bird() {  	alert(“bird created”); }  var crow= new Bird();  varcannary= new Bird();  The constructor is called each time the instance is created
The Object Creating and populating an object var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12); var owner = new Object();         owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;
The Object object hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in objects
The Object Accessing values from object $(document).ready(function () {             $(".container").append("<tr><td>Make</td><td>" + ride.make + "</td></tr>");             $(".container").append("<tr><td>Model</td><td>" + ride.model + "</td></tr>");             $(".container").append("<tr><td>Year</td><td>" + ride.year + "</td></tr>");             $(".container").append("<tr><td>Purchased</td><td>" + ride.purchased + "</td></tr>");             $(".container").append("<tr><td>Owner Name</td><td>" + ride.owner.name + "</td></tr>");             $(".container").append("<tr><td>Owner Occupation</td><td>" + ride.owner.occupation + "</td></tr>");         }); Another way of accessing properties ride["Clumsy Property"] = 'Really clumsy value'; $(".container").append("<tr><td>Clumsy Value</td><td>" + ride["Clumsy Property"] + "</td></tr>"); This is useful for names that have spaces / (.) dots
Object Literals (JSON) var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12);         ride["Clumsy Property"] = 'Really clumsy value'; var owner = new Object();         owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner; varrideJSON = {             make: 'Yamaha',             model: 'V-Star Silverado 1100',             year: 2005,             purchased: new Date(2005, 3, 12),             'Clumsy Property' : 'Really clumsy value',             owner: {                 name: 'Spike Spiegel',                 occupation: 'bounty hunter'             }         }; JavaScript Object Notation allows us to define object using literals 	- we no longer need to instantiate new Object() 	- reduces the work of defining name and then assigning value
JSON : Rules for definition {      "firstName": "John",      "lastName": "Smith",      "age": 25,      "address":      {          "streetAddress": "21 2nd Street",          "city": "New York",          "state": "NY",          "postalCode": "10021"      },      "phoneNumber":      [          {            "type": "home",            "number": "212 555-1234"          },          {            "type": "fax",            "number": "646 555-4567"          }      ]  } { defines start of a an object. } defines the end. [ defines start of an array. ] defines the end. Name and values are separated by :
Summary so far A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using  new Object() object literals instantiating a “class” Top-level variables are properties of window. all of the following statements are equivalent: varfoo = bar; and window.foo = bar; and foo = bar;
Functions Similar to any other type Function instances are values that can be assigned to variables, properties, or parameters just like instances of other object types Following are the same : function hello(){ alert('Hi there!'); }  hello = function(){ alert('Hi there!'); } window.hello = function(){ alert('Hi there!'); }
Functions : adding as property var ride = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005,3,12), owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'}, whatAmI: function() { return this.year+' '+this.make+' '+this.model; } };
Functions contd.
Functions contd. Functions can be passed as parameter  setTimeout(function() { alert('Hi there!'); },5000); Context in function object referenced by this—termed the function context In the default case, the context (this) of an invocation of the function is the object whose property contains the reference used to invoke the function If you are using call(), you can specify the context and params
Function Context Function context describes the object that’s referenced by the this pointer during the invocation of a function. var o1 = {handle:'o1'}; var o2 = {handle:'o2'}; var o3 = {handle:'o3'}; window.handle = 'window';       function whoAmI(messageText) {         return this.handle + " , message text : " + messageText;      }       o1.identifyMe = whoAmI;       alert(whoAmI("message text window"));       alert(o1.identifyMe("message text o1"));       alert(whoAmI.call(o2, "message text o2"));       alert(whoAmI.apply(o3, "message text o3")); A function f acts as a method of object o when o serves as the function context of the invocation of f.
Anonymous Functions Declaring functions inline rather than separately IF IT IS USED ONLY ONCE. var employee2 = { empID: 57, firstName: 'Gunjan', lastName: 'Kumar', whoAmI: function () {                 return "Emp ID : " + this.empID + " First Name : " + this.firstName + " Last Name : " + this.lastName;             }         }; These are faster since name resolution is costly Should be typically used when system does a call – like windows.onload 	When you are going to call, typically named functions are used
Prototype Allows you to add new properties / methods to class Helps in implementing inheritance of sorts – you can instantiate objects of older type and then add additional properties to the “class” Advantages You can add methods to “classes” you didn’t create the functions are only stored once (in the prototype object), rather than in every new object When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype
Prototype example String.prototype.convertUnderscores = function () {             return this.replace(/_/g, " ");         }; var underscored = "Are_there_any_spaces_in_here?"; var spaced = underscored.convertUnderscores();         alert(spaced);         function Bird() { this.feet = 2; this.feathers = true;             return true;         } var bird1 = new Bird();         alert(bird1.getFeetNum); Bird.prototype.getFeetNum = function () {             return this.feet;         }; var bird2 = new Bird();         alert(bird2.getFeetNum());
Inheritance using prototype function Bird() { this.feet = 2; this.feathers = true;             return true;         }  function Canary() { this.color = "yellow";             return true;         } Canary.prototype = new Bird(); //defining parent class if you will vartweety = new Canary();         alert("Feet : " + tweety.feet +  	" Color : " + tweety.color + 	" Feathers : " + tweety.feathers); function Crow() { this.superclass = Bird; this.superclass(); this.color = "black";             return true;         }
Inheritance using prototype // define the Person Class   function Person() { } Person.prototype.sayHello = function () {            alert('hello');        }; // define the Student class function Student() { } // inherit Person Student.prototype = new Person(); // correct the constructor pointer because it points to Person Student.prototype.constructor = Student; // replace the sayHello method Student.prototype.sayHello = function () {            alert('hi, I am a student');        } // add sayGoodBye method Student.prototype.sayGoodBye = function () {            alert('goodBye');        } var student1 = new Student(); student1.sayHello(); student1.sayGoodBye();
Namespace No inherent way to prevent name conflict – if 2 people define same named “class”, the later definition will be used. Namespace is implemented by typically using domain names with the class name BUT that implies each part of the Domain Name has to be defined
Namespace example if (typeof com == "undefined") {             com = new Object();         }         if (typeofcom.qwest == "undefined") { com.qwest = new Object();         } com.qwest.Bird = function() { this.feet = 2; this.feathers = true; this.color = "yellow";             return true;         }         Bird = function () { this.feet = 2; this.feathers = true; this.color = "black";             return true;         }
Closure Closure is a Function instance coupled with the local variables from its environment that are necessary for its execution. How this manifests : For a function, a variable defined in its scope at the point of declaration, is carried along with the function even after the point of declaration has gone out of scope, closing the declaration $(function () { var local = 1; window.setInterval(function () {                 $('#display')             .append('<div>At ' + new Date() + ' local=' + local + '</div>');                 local++;             }, 3000);         });
Closure contd. Another important feature of closures is that a function context is never included as part of the closure. this.id = 'someID'; $('*').each(function(){ alert(this.id); }); Here this.id will give the id property for the function context of each which is NOT same as the one with someID this.id = 'someID'; var outer = this; $('*').each(function(){ alert(outer.id); }); Here , the variable outer is defined in the scope of the function and hence by closure, it can access the same
Unobtrusive JavaScript What is it? Not a formal term but refers to an approach on how to use JavaScript in web pages Primarily talks about separation of behavior from presentation (sounds familiar??) <input type="text" name="date" onchange="validateDate()" /> Vs. <input type="text" name="date" id="date" /> $(function(){     $('#date').bind('change', validateDate); });
Unobtrusive JavaScript (contd.) purpose of markup is to describe a structure combining the structure and behavior negatively impacts maintainability  inline event handlers are harder to use and maintain specially  when one needs to set handlers for several events on a single element 	when one wants to set the same event handler on several elements 	when one is using event delegation In essence, this is asking for a separate .JS file that contains all the behavior and attaches the same to markup. Typically this would result in three set of files Html (markup) CSS (presentation) JS (behavior)
Unobtrusive JavaScript  Reference Reference : http://en.wikipedia.org/wiki/Unobtrusive_JavaScript http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html http://labs.adobe.com/technologies/spry/articles/best_practices/separating_behavior.html
JSON References http://en.wikipedia.org/wiki/JSON http://www.json.org/ http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_) http://www.jsonlint.com/ : this allows you to validate / format json string https://github.com/douglascrockford/JSON-js varmyJSONText = JSON.stringify(myObject)  varmyObject = JSON.parse(myJSONtext) http://api.jquery.com/jQuery.parseJSON/http://api.jquery.com/jQuery.getJSON/ varobj = jQuery.parseJSON('{"name":"John"}'); 	alert( obj.name === "John" );

Weitere Àhnliche Inhalte

Was ist angesagt?

eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOMJalpesh Vasa
 
Ios development
Ios developmentIos development
Ios developmentelnaqah
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreXavier Coulon
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersJoris Verbogt
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OOJohn Hunter
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar LanguageDr. Jan Köhnlein
 
Java script
 Java script Java script
Java scriptbosybosy
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java DevelopersBob McCune
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysisUchitha Bandara
 
Object Calisthenics em Go
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em GoElton Minetto
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeMitchell Tilbrook
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsHazem Hagrass
 

Was ist angesagt? (20)

eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
Week3
Week3Week3
Week3
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
05 ruby classes
05 ruby classes05 ruby classes
05 ruby classes
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
 
Ios development
Ios developmentIos development
Ios development
 
DevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a DatastoreDevNation'15 - Using Lambda Expressions to Query a Datastore
DevNation'15 - Using Lambda Expressions to Query a Datastore
 
Composite Pattern
Composite PatternComposite Pattern
Composite Pattern
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 
Javascript foundations: Introducing OO
Javascript foundations: Introducing OOJavascript foundations: Introducing OO
Javascript foundations: Introducing OO
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Java script
 Java script Java script
Java script
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Object Calisthenics em Go
Object Calisthenics em GoObject Calisthenics em Go
Object Calisthenics em Go
 
JavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React NativeJavaScript, TypeScipt and React Native
JavaScript, TypeScipt and React Native
 
Op ps
Op psOp ps
Op ps
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 

Ähnlich wie OO in JavaScript

11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objectsPhĂșc Đỗ
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript LiteracyDavid Jacobs
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript WorkshopPamela Fox
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templatingbcruhl
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposalSlavisa Pokimica
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsSubramanyan Murali
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindiappsdevelopment
 
Web Host_G4.pptx
Web Host_G4.pptxWeb Host_G4.pptx
Web Host_G4.pptxRNithish1
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
Coding Ajax
Coding AjaxCoding Ajax
Coding AjaxTed Husted
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesRay Toal
 

Ähnlich wie OO in JavaScript (20)

Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
 
11. session 11 functions and objects
11. session 11   functions and objects11. session 11   functions and objects
11. session 11 functions and objects
 
JavaScript Literacy
JavaScript LiteracyJavaScript Literacy
JavaScript Literacy
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
JavaScript Workshop
JavaScript WorkshopJavaScript Workshop
JavaScript Workshop
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Javascript
JavascriptJavascript
Javascript
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
 
ActionScript3 collection query API proposal
ActionScript3 collection query API proposalActionScript3 collection query API proposal
ActionScript3 collection query API proposal
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Synapseindia object oriented programming in php
Synapseindia object oriented programming in phpSynapseindia object oriented programming in php
Synapseindia object oriented programming in php
 
Web Host_G4.pptx
Web Host_G4.pptxWeb Host_G4.pptx
Web Host_G4.pptx
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
Modeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based GamesModeling Patterns for JavaScript Browser-Based Games
Modeling Patterns for JavaScript Browser-Based Games
 

KĂŒrzlich hochgeladen

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂșjo
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
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 SavingEdi Saputra
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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...DianaGray10
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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, Adobeapidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 

KĂŒrzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 

OO in JavaScript

  • 1. OO in JavaScript Gunjan Kumar
  • 2. Agenda JavaScript you need to know OO in JavaScript OO basics Inheritance Encapsulation Polymorphism Class Object and properties Object literals (JSON) Functions and function context, Anonymous functions Prototype and inheritance Closure unobtrusive JavaScript - the way our code should be structured
  • 3. OO in JS Prototype-based programming is a style of object-oriented programming in which classes are not present behavior reuse (inheritance) is accomplished through a process of decorating existing objects which serve as prototypes. This model is also known as class-less, prototype-oriented, or instance-based programming. Support in JS : Inheritance - The ability to define the behavior of one object in terms of another by sub-classing. Encapsulation - Support for method calls on a JavaScript object as a member of a Class Polymorphism - The ability for two classes to respond to the same (collection of) methods.
  • 4. Inheritance Inheritance allows one class to replicate and extend the functionality of another without having to re-implement the existing class’s behavior JavaScript only supports single class inheritance Supported by prototype and other options in JS More details later in the slides
  • 5. Encapsulation Encapsulation ensures that an object’s state can only be changed by the object itself, as a result of that object’s performing one of the operations (methods) it supports. Supported by defining variables in function with this. And then defining functions to access these variables function A(){ var x = 7; this.GetX = function () { return x; } this.SetX = function (xT) { x = xT; } } obj = new A; obj2 = new A; document.write(obj.GetX() + ' ' + obj2.GetX()); obj.SetX(14); document.write(' ' + obj.GetX() + ' ' + obj2.GetX()); //alert(obj.x);//gives undefined
  • 6. Abstraction Abstraction key concept that underpins the very notion of objects - that they abstract the details of their own implementation. This can be achieved by inheritance (specialization), or composition. JavaScript achieves specialization by inheritance, and composition by letting instances of classes be the values of attributes of other objects
  • 7. Polymorphism Polymorphism ability to appear in different forms. allows an object of a given class to be treated as if it were an object of its superclass, despite the fact that one or more of the superclass’s methods may be defined differently (overridden) in the object’s true class. In JS, different classes can define methods with the same name; methods are scoped to the class in which they're defined. Achieved by simply having different object classes implement a collection of methods that use the same names. Then, a caller, need just use the correctly named function property to invoke the appropriate function for each object type.
  • 8. Polymorphism function A() { this.x = 1; } A.prototype.DoIt = function() // Define Method { this.x += 1; } function B() { this.x = 1; } B.prototype.DoIt = function() // Define Method { this.x += 2; } a = new A; b = new B; a.DoIt(); b.DoIt(); document.write(a.x + ', ' + b.x);
  • 9. The Class JavaScript is a prototype-based language which contains no class statement, such as is found in C++ or Java. This is of relevance ONLY if we expect multiple objects with same properties – thus reducing the lines of code No formal way to define a class. Any function definition is a class Properties and methods can be defined within the function To instantiate, we use the new keyword We can define the function to accept parameters to simulate a constructor which sets default params
  • 10. The Class function Owner(_name, _age) { this.name = _name; this.age = _age; } function Bike(_name, _model, _make, _mileage, _owner) { this.name = _name; this.model = _model; this.make = _make; this.mileage = _mileage; this.owner = _owner; this.whatAmI = function () { return this.year + ' ' + this.make + ' ' + this.model; } } var bike3 = new Bike('Yamaha3', 'Model 3', new Date(2008, 3, 12), 33, new Owner('owner 3', 33));
  • 11. The Object Create object by new Object() No properties by default. Keep adding dynamically. primary purpose of an Object instance to serve as a container for a named collection of other objects The name of a property is a string Value can be any JavaScript object, be it a Number, String, Date, Array, basic Object, or any other JavaScript object type (including functions)
  • 12. The Object You can also create instance of the Class function Bird() { alert(“bird created”); } var crow= new Bird(); varcannary= new Bird(); The constructor is called each time the instance is created
  • 13. The Object Creating and populating an object var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12); var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner;
  • 14. The Object object hierarchy shows that Objects are containers for named references to other Objects or JavaScript built-in objects
  • 15. The Object Accessing values from object $(document).ready(function () { $(".container").append("<tr><td>Make</td><td>" + ride.make + "</td></tr>"); $(".container").append("<tr><td>Model</td><td>" + ride.model + "</td></tr>"); $(".container").append("<tr><td>Year</td><td>" + ride.year + "</td></tr>"); $(".container").append("<tr><td>Purchased</td><td>" + ride.purchased + "</td></tr>"); $(".container").append("<tr><td>Owner Name</td><td>" + ride.owner.name + "</td></tr>"); $(".container").append("<tr><td>Owner Occupation</td><td>" + ride.owner.occupation + "</td></tr>"); }); Another way of accessing properties ride["Clumsy Property"] = 'Really clumsy value'; $(".container").append("<tr><td>Clumsy Value</td><td>" + ride["Clumsy Property"] + "</td></tr>"); This is useful for names that have spaces / (.) dots
  • 16. Object Literals (JSON) var ride = new Object(); ride.make = 'Yamaha'; ride.model = 'V-Star Silverado 1100'; ride.year = 2005; ride.purchased = new Date(2005, 3, 12); ride["Clumsy Property"] = 'Really clumsy value'; var owner = new Object(); owner.name = 'Spike Spiegel'; owner.occupation = 'bounty hunter'; ride.owner = owner; varrideJSON = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005, 3, 12), 'Clumsy Property' : 'Really clumsy value', owner: { name: 'Spike Spiegel', occupation: 'bounty hunter' } }; JavaScript Object Notation allows us to define object using literals - we no longer need to instantiate new Object() - reduces the work of defining name and then assigning value
  • 17. JSON : Rules for definition { "firstName": "John", "lastName": "Smith", "age": 25, "address": { "streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": "10021" }, "phoneNumber": [ { "type": "home", "number": "212 555-1234" }, { "type": "fax", "number": "646 555-4567" } ] } { defines start of a an object. } defines the end. [ defines start of an array. ] defines the end. Name and values are separated by :
  • 18. Summary so far A JavaScript object is an unordered collection of properties. Properties consist of a name and a value. Objects can be declared using new Object() object literals instantiating a “class” Top-level variables are properties of window. all of the following statements are equivalent: varfoo = bar; and window.foo = bar; and foo = bar;
  • 19. Functions Similar to any other type Function instances are values that can be assigned to variables, properties, or parameters just like instances of other object types Following are the same : function hello(){ alert('Hi there!'); } hello = function(){ alert('Hi there!'); } window.hello = function(){ alert('Hi there!'); }
  • 20. Functions : adding as property var ride = { make: 'Yamaha', model: 'V-Star Silverado 1100', year: 2005, purchased: new Date(2005,3,12), owner: {name: 'Spike Spiegel',occupation: 'bounty hunter'}, whatAmI: function() { return this.year+' '+this.make+' '+this.model; } };
  • 22. Functions contd. Functions can be passed as parameter setTimeout(function() { alert('Hi there!'); },5000); Context in function object referenced by this—termed the function context In the default case, the context (this) of an invocation of the function is the object whose property contains the reference used to invoke the function If you are using call(), you can specify the context and params
  • 23. Function Context Function context describes the object that’s referenced by the this pointer during the invocation of a function. var o1 = {handle:'o1'}; var o2 = {handle:'o2'}; var o3 = {handle:'o3'}; window.handle = 'window'; function whoAmI(messageText) { return this.handle + " , message text : " + messageText; } o1.identifyMe = whoAmI; alert(whoAmI("message text window")); alert(o1.identifyMe("message text o1")); alert(whoAmI.call(o2, "message text o2")); alert(whoAmI.apply(o3, "message text o3")); A function f acts as a method of object o when o serves as the function context of the invocation of f.
  • 24. Anonymous Functions Declaring functions inline rather than separately IF IT IS USED ONLY ONCE. var employee2 = { empID: 57, firstName: 'Gunjan', lastName: 'Kumar', whoAmI: function () { return "Emp ID : " + this.empID + " First Name : " + this.firstName + " Last Name : " + this.lastName; } }; These are faster since name resolution is costly Should be typically used when system does a call – like windows.onload When you are going to call, typically named functions are used
  • 25. Prototype Allows you to add new properties / methods to class Helps in implementing inheritance of sorts – you can instantiate objects of older type and then add additional properties to the “class” Advantages You can add methods to “classes” you didn’t create the functions are only stored once (in the prototype object), rather than in every new object When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype
  • 26. Prototype example String.prototype.convertUnderscores = function () { return this.replace(/_/g, " "); }; var underscored = "Are_there_any_spaces_in_here?"; var spaced = underscored.convertUnderscores(); alert(spaced); function Bird() { this.feet = 2; this.feathers = true; return true; } var bird1 = new Bird(); alert(bird1.getFeetNum); Bird.prototype.getFeetNum = function () { return this.feet; }; var bird2 = new Bird(); alert(bird2.getFeetNum());
  • 27. Inheritance using prototype function Bird() { this.feet = 2; this.feathers = true; return true; } function Canary() { this.color = "yellow"; return true; } Canary.prototype = new Bird(); //defining parent class if you will vartweety = new Canary(); alert("Feet : " + tweety.feet + " Color : " + tweety.color + " Feathers : " + tweety.feathers); function Crow() { this.superclass = Bird; this.superclass(); this.color = "black"; return true; }
  • 28. Inheritance using prototype // define the Person Class function Person() { } Person.prototype.sayHello = function () { alert('hello'); }; // define the Student class function Student() { } // inherit Person Student.prototype = new Person(); // correct the constructor pointer because it points to Person Student.prototype.constructor = Student; // replace the sayHello method Student.prototype.sayHello = function () { alert('hi, I am a student'); } // add sayGoodBye method Student.prototype.sayGoodBye = function () { alert('goodBye'); } var student1 = new Student(); student1.sayHello(); student1.sayGoodBye();
  • 29. Namespace No inherent way to prevent name conflict – if 2 people define same named “class”, the later definition will be used. Namespace is implemented by typically using domain names with the class name BUT that implies each part of the Domain Name has to be defined
  • 30. Namespace example if (typeof com == "undefined") { com = new Object(); } if (typeofcom.qwest == "undefined") { com.qwest = new Object(); } com.qwest.Bird = function() { this.feet = 2; this.feathers = true; this.color = "yellow"; return true; } Bird = function () { this.feet = 2; this.feathers = true; this.color = "black"; return true; }
  • 31. Closure Closure is a Function instance coupled with the local variables from its environment that are necessary for its execution. How this manifests : For a function, a variable defined in its scope at the point of declaration, is carried along with the function even after the point of declaration has gone out of scope, closing the declaration $(function () { var local = 1; window.setInterval(function () { $('#display') .append('<div>At ' + new Date() + ' local=' + local + '</div>'); local++; }, 3000); });
  • 32. Closure contd. Another important feature of closures is that a function context is never included as part of the closure. this.id = 'someID'; $('*').each(function(){ alert(this.id); }); Here this.id will give the id property for the function context of each which is NOT same as the one with someID this.id = 'someID'; var outer = this; $('*').each(function(){ alert(outer.id); }); Here , the variable outer is defined in the scope of the function and hence by closure, it can access the same
  • 33. Unobtrusive JavaScript What is it? Not a formal term but refers to an approach on how to use JavaScript in web pages Primarily talks about separation of behavior from presentation (sounds familiar??) <input type="text" name="date" onchange="validateDate()" /> Vs. <input type="text" name="date" id="date" /> $(function(){ $('#date').bind('change', validateDate); });
  • 34. Unobtrusive JavaScript (contd.) purpose of markup is to describe a structure combining the structure and behavior negatively impacts maintainability inline event handlers are harder to use and maintain specially when one needs to set handlers for several events on a single element when one wants to set the same event handler on several elements when one is using event delegation In essence, this is asking for a separate .JS file that contains all the behavior and attaches the same to markup. Typically this would result in three set of files Html (markup) CSS (presentation) JS (behavior)
  • 35. Unobtrusive JavaScript Reference Reference : http://en.wikipedia.org/wiki/Unobtrusive_JavaScript http://icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/ http://www.onlinetools.org/articles/unobtrusivejavascript/chapter1.html http://labs.adobe.com/technologies/spry/articles/best_practices/separating_behavior.html
  • 36. JSON References http://en.wikipedia.org/wiki/JSON http://www.json.org/ http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_) http://www.jsonlint.com/ : this allows you to validate / format json string https://github.com/douglascrockford/JSON-js varmyJSONText = JSON.stringify(myObject) varmyObject = JSON.parse(myJSONtext) http://api.jquery.com/jQuery.parseJSON/http://api.jquery.com/jQuery.getJSON/ varobj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" );
  • 37. OO Reference https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript PDFs from earlier training sessions (to be shared) http://mckoss.com/jscript/object.htm : very nicely explains inheritance, polymorphism and encapsulation in JS
  • 38. Thank You  gunjankumar300@gmail.com http://in.linkedin.com/in/gunjankumar300