• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
OO in JavaScript

OO in JavaScript



Introduction to OO in JavaScript

Introduction to OO in JavaScript



Total Views
Views on SlideShare
Embed Views



3 Embeds 10

http://www.linkedin.com 7 2
https://www.linkedin.com 1


Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    OO in JavaScript OO in JavaScript Presentation Transcript

    • OO in JavaScript
      Gunjan Kumar
    • Agenda
      JavaScript you need to know
      OO in JavaScript
      OO basics
      Object and properties
      Object literals (JSON)
      Functions and function context,
      Anonymous functions
      Prototype and inheritance
      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
      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
      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());
      document.write(' ' + obj.GetX() + ' ' + obj2.GetX());
      //alert(obj.x);//gives undefined
    • 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
      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;
      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,
      "streetAddress": "21 2nd Street",
      "city": "New York",
      "state": "NY",
      "postalCode": "10021"
      "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”
      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();
      function Bird() {
      this.feet = 2;
      this.feathers = true;
      return true;
      var bird1 = new Bird();
      Bird.prototype.getFeetNum = function () {
      return this.feet;
      var bird2 = new Bird();
    • 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.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();
    • 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 () {
      .append('<div>At ' + new Date() + ' local=' + local + '</div>');
      }, 3000);
    • Closure contd.
      Another important feature of closures is that a function context is never included as part of the closure.
      this.id = 'someID';
      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;
      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()" />
      <input type="text" name="date" id="date" />
      $('#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 :
    • JSON References
      http://www.jsonlint.com/ : this allows you to validate / format json string
      varmyJSONText = JSON.stringify(myObject)
      varmyObject = JSON.parse(myJSONtext)
      varobj = jQuery.parseJSON('{"name":"John"}');
      alert( obj.name === "John" );
    • OO Reference
      PDFs from earlier training sessions (to be shared)
      http://mckoss.com/jscript/object.htm : very nicely explains inheritance, polymorphism and encapsulation in JS
    • Thank You 