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.
- var ClassA = function() {
- this.Name = "tanuj";
- };
- var a = new ClassA(); // object creation
- ClassA.prototype.print = function() { // further Add Any thing in object on the fly.
- console.log(this.Name);
- };
- var inheritfrom = function(child, parent) { // Generic function for Any inheritance
- child.prototype = Object.create(parent.prototype) // cloneing the protitype
- };
- var ClassB = function() // Class 2
- {
- this.name = "in Class 2";
- this.surname = "i am child";
- console.log(this.surname + this.name);
- };
- inheritfrom(ClassB, ClassA); // Actual inheritance
- a.print(); // function call from class
- var b = new ClassB(); // object creation
- b.print(); // calling base class function from child object
- // overriding the print function of Class B
- ClassB.prototype.print = function() {
- ClassA.prototype.print.call(this); // overloading
- console.log("B callong overload");
- };
- b.print();
- /// Class C inheritance
- var ClassC = function() { // Class C
- this.name = "Class C name";
- this.surname = "Class C Surname";
- };
- inheritfrom(ClassC, ClassB);
- ClassC.prototype.foo = function() {
- console.log("in class C foo");
- };
- ClassC.prototype.print = function() { // overriding
- ClassB.prototype.print.call(this);
- console.log("overriding in Class C");
- };
- var C = new ClassC();
- C.print();

Join the conversation! Your thoughts help the community grow.