Share on facebook
Facebook
Share on twitter
Twitter

Almost OOP: Simple Inheritance with JavaScript

A lot of my friends are C# or C++ developers. They are used to use inheritance in their projects and when they want to learn or discover JavaScript, one of the first question they ask is: “But how can I do inheritance with JavaScript?” Actually, JavaScript uses a different approach than C# or C++ to create an object-oriented language. It is a prototype-based language. The concept of prototyping implies that behavior can be reused by cloning existing objects that serve as prototypes. Every object in JavaScript depends from a prototype which defines a set of functions and members that the object can use. There is no class. Just objects. Every object can then be used as prototype for another object. This concept is extremely flexible and we can use it to simulate some concepts from OOP like inheritance. Implementing inheritance Let’s image what we want to create with this hierarchy using JavaScript: First of all, we can create ClassA easily. Because there is no explicit classes, we can define a set of behavior (A class so…) by just creating a function like this: 1 2 3 var ClassA = function() { this.name = “class A”; } This “class” can be […]

X