OO in JavaScript


Published on

Introduction to OO in JavaScript

Published in: Technology, News & Politics
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

OO in JavaScript

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

    Clipping is a handy way to collect important slides you want to go back to later.