JavaScript is a object based language and Java is a object oriented language. There are lot of object oriented features comes with java like static and non-static members, private and public members, inheritance etc. So why can't we have all these in JavaScript??? After googling and discussing with some of the JavaScript developers, finally we could able to demonstrate the object oriented features using JavaScript. We made use of JavaScript function and prototype to achieve this.
Work Flow:
1. One base class is created.
2. Another child class created extending the base class to demonstrate the inheritance.
3. One subclass created extending the second class to demonstrate the multilevel inheritance.
I am sharing the source code to better understand, what we did.
Note:
1. All the classes will be having static, non-static, private and public members.
2. In the test client we are demonstrating some of these features.
3. To test the other features, additional caller codes has to be added.
4. What ever we worked out is not the actual object oriented features in JavaScript. But certainly works like that.
5. There can be many other ways to do the same.
Shared Items:
1. Source Code
Really great work. Good thought
ReplyDeletevar Shape = Class.extend({
ReplyDeleteinit: function(height, width) {
this.height = height;
this.width = width;
},
info: function() {
alert("I have height = " + this.height +
" and width = " + this.width);
}
});
var Rectangle = Shape.extend({
});
var Square = Rectangle.extend({
init: function(size) {
this.inherited().init(size, size);
}
});
var rectangle = new Rectangle(5, 10);
var square = new Square(10);
rectangle.info(); // it will alert => I have height = 5 and width = 10
square.info(); // it will alert => I have height = 10 and width = 10