Nothing can do this job better than the object oriented programming!
So we use this “shared object” to achieve inheritance.
In the image bellow I defined a class Animal
The constructor takes a config object with age and name fields. Age is kept as a private class variable and name is stored as a public class field. Private scope in JS is achieved using var keyword. In this way “_age” lives just in the scope of constructor function Animal and behaves like a private class field. I defined two functions getAge and setAge to manipulate the private field “_age”. Have in mind that you can add functions and properties to the prototype of a given class outside it`s constructor:
Note: Using this approach we do not have access to the private class field (in our case “_age”).
Now we have class Animal with one private and one public field and 3 functions.
Let`s inherit the Animal Class:
The key of inheritance here is the line:
Cat.prototype = new Animal();
Another words the prototype of the class Cat becomes and instance of the Animal class and in this way it has all its fields and functions.
One very important part of all the magic here is to pass the configuration object to the Animal constructor:
I added function sayMiau and breed field just to show that Cat can have it`s own functions and fields.
Let`s do some tests of the written above:
In the next example I extended the String prototype by adding the c#-like format function:
You can see the code of all the examples here: