Object Oriented JavaScript

Introduction

 
JavaScript is a prototype-based programming language, which has no class as C++, C#, Java etc. JavaScript uses functions as the classes.
You can define a private or local variable inside a class by using var keyword. When you define a variable without var keyword inside a class, it acts as a public variable.
 
Prototype-based programming is a style of an object-oriented programming in which classes are not present and code re-usability or inheritance is achieved by decorating existing objects, which acts as prototypes. This programming style is also known as class-less, prototype-oriented or instance-based programming.
  1. var ClassA = function() {  
  2.     this.Name = "tanuj";  
  3. };  
  4. var a = new ClassA(); // object creation  
  5. ClassA.prototype.print = function() { // further Add Any thing in object on the fly.  
  6.     console.log(this.Name);  
  7. };  
  8. var inheritfrom = function(child, parent) { // Generic function for Any inheritance  
  9.     child.prototype = Object.create(parent.prototype) // cloneing the protitype  
  10. };  
  11. var ClassB = function() // Class 2  
  12. {  
  13.     this.name = "in Class 2";  
  14.     this.surname = "i am child";  
  15.     console.log(this.surname + this.name);  
  16. };  
  17. inheritfrom(ClassB, ClassA); // Actual inheritance  
  18. a.print(); // function call from class  
  19. var b = new ClassB(); // object creation  
  20. b.print(); // calling base class function from child object  
  21. // overriding the print function of Class B  
  22. ClassB.prototype.print = function() {  
  23.     ClassA.prototype.print.call(this); // overloading  
  24.     console.log("B callong overload");  
  25. };  
  26. b.print();  
  27. /// Class C inheritance  
  28. var ClassC = function() { // Class C  
  29.     this.name = "Class C name";  
  30.     this.surname = "Class C Surname";  
  31. };  
  32. inheritfrom(ClassC, ClassB);  
  33. ClassC.prototype.foo = function() {  
  34.     console.log("in class C foo");  
  35. };  
  36. ClassC.prototype.print = function() { // overriding  
  37.     ClassB.prototype.print.call(this);  
  38.     console.log("overriding in Class C");  
  39. };  
  40. var C = new ClassC();  
  41. C.print();