12/08/2018, 16:17

Object-Oriented JavaScript

With the article, We continue with object in javascript about OOP, with my last article Object in Javascript, If you don't understand what is the object in javascript or before read this article you need to read my previous article first about Object In Javascript . In this article too, you will ...

With the article, We continue with object in javascript about OOP, with my last article Object in Javascript, If you don't understand what is the object in javascript or before read this article you need to read my previous article first about Object In Javascript. In this article too, you will listen the one meaning of OOP is Object Create pattern ([Encapsulation])(https://en.wikipedia.org/wiki/Encapsulation_(computer_programming)) and Code Reuse pattern (Inheritance) . When building applications, you create many objects, and there exist many ways for creating these objects sourece image: https://docs.sencha.com/extjs/6.0.2/guides/other_resources/oop_concepts.html

Encapslution in Javascript

(The Best Object Creation Pattern: Combination Constructor/Prototype Pattern) As discussed above, one of the main principles with OOP is encapsulation: put all the inner workings of an object inside that object. To implement encapsulation in JavaScript, we have to define the core methods and properties on that object. To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern. This name is a mouthful, but you needn’t memorize it, since we are only concerned with its implementation. Before we implement it, let’s quickly learn a bit more about the practicality of encapsulation. example:

function Book(title, price) {
    this.title = title;
    this.price = price;
    this.ranges = [];
    this.codeNumber =  0;
}

Book.protoype =  {
    constructor: Book,
    saveRange: function(range) {
        this.ranges.push(range);
    },
    showTitleAndRanges: function() {
        var ranges = this.ranges.length > 0 ? this.ranges.join(',') : 'Out of range';
        return this.title + ', Ranges: ' + ranges; 
    },
    changeTitle: function(newTitle) {
        this.title = newTitle;
        return 'New Title Saved:' + this.title;
    }
}

Make Instances of the Book function

// A Book
firstBook = new Book('Javascript', 600);
firstBook.changeTitle('Ruby');
firstBook.saveRange(7);
firstBook.saveRange(10);

firstBook.showTitleAndRanges();  // Ruby, Ranges: 7, 10

secondBook = new Book('C#', 100);
secondBook.saveRange(18);
secondBook.showTitleAndRages(); // C#, Ranges: 18

Combination Constructor/Prototype Pattern (Explanation)

Let’s expound on each line of code so we have a thorough understanding of this pattern.

The following lines initialize the instance properties. These properties will be defined on each User instance that is created. So the values will be different for each user. The use of the this keyword inside the function specifies that these properties will be unique to every instance of the Book object:

    this.title = title;
    this.price = price;
    this.ranges = [];
    this.codeNumber = 0;

In code below we are overriding the prototype property with an object literal, and we define all of our methods (that will be inherited by all the Book instance) in this object. However we don't override the constructor with Book.prototype each time like below:

 Book.prototype.constructor = Book;
 Book.prototype.saveRange = function (range) {
     this.ranges.push(range);
 };
 
  Book.prototype.showTitleAndRanges  = function() {
      var ranges = this.ranges.length > 0 ? this.ranges.join(',') : 'Out of range';
      return this.title + ', Ranges: ' + ranges; 
  };
  
  Book.prototype.changeTitle = function(newTitle) {
      this.title = newTitle;
      return 'New Title Saved:' + this.title;
  };

By overwriting the prototype with a new object literal we have all the methods organized in one place, and you can better see the encapsulation that we are after. And of course it is less code you have to type.

Inheritance in JavaScript

(The Best Pattern: Parasitic Combination Inheritance)

Implementing inheritance in our quiz application will permit us to inherit functionality from parent Functions so that we can easily reuse code in our application and extend the functionality of objects. Objects can make use of their inherited functionalities and still have their own specialized functionalities.

The best pattern for implementing inheritance in JavaScript is the Parasitic Combination inheritance 2. Before we dive into this awesome pattern, let’s see why its practical to use inheritance in our applications.

We have successfully implemented encapsulation by enclosing all the functionality for users of our quiz application by adding all the methods and properties that each user will need on the User function, and all instances of User will have those properties and methods.

When do we use inheritance ?

Let's start simple example about this,

var ClassA = function() {
    this.name = "class A";
}

ClassA.prototype.print = function() {
    console.log(this.name);
}

var a = new ClassA();

a.print();

Now let’s add a tool to create “inheritance” between classes. This tool will just have to do one single thing: clone the prototype:

var inheritsFrom = function (child, parent) {
    child.prototype = Object.create(parent.prototype);
};

This is exactly where the magic happens! By cloning the prototype, we transfer all members and functions to the new class.

So if we want to add a second class that will be a child of the first one, we just have to use this code:

var ClassB = function() {
    this.name = "class B";
    this.surname = "I'm the child";
}

inheritsFrom(ClassB, ClassA);

Then because ClassB inherited the print function from ClassA, the following code is working:

var b = new ClassB();
b.print();

The trick here is to the call ClassA.prototype to get the base print function. Then thanks to call function we can call the base function on the current object (this). Creating ClassC is now obvious:

var ClassC = function () {
    this.name = "class C";
    this.surname = "I'm the grandchild";
}

inheritsFrom(ClassC, ClassB);

ClassC.prototype.foo = function() {
    // Do some funky stuff here...
}

ClassC.prototype.print = function () {
    ClassB.prototype.print.call(this);
    console.log("Sounds like this is working!");
}

var c = new ClassC();
c.print();

Result will be look like this:

class C 
I’m the grandchild 
Sounds like this is working!

Conclusion

I gave you the full details for implementing the best two patterns for OOP in JavaScript, and I am hopeful you understood at least the general concepts. Go use these patterns in your JavaScript applications. Note that you can use OOP in even small and medium applications, not just complex applications.

  • Professional JavaScript for Web Developers
  • http://javascript.crockford.com/prototypal.html
0