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();
- ClassA.prototype.print = function() {
- console.log(this.Name);
- };
- var inheritfrom = function(child, parent) {
- child.prototype = Object.create(parent.prototype)
- };
- var ClassB = function()
- {
- this.name = "in Class 2";
- this.surname = "i am child";
- console.log(this.surname + this.name);
- };
- inheritfrom(ClassB, ClassA);
- a.print();
- var b = new ClassB();
- b.print();
-
- ClassB.prototype.print = function() {
- ClassA.prototype.print.call(this);
- console.log("B callong overload");
- };
- b.print();
-
- var ClassC = function() {
- 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() {
- ClassB.prototype.print.call(this);
- console.log("overriding in Class C");
- };
- var C = new ClassC();
- C.print();