Javascript Concepts Simplified Part 2: Javascript Inheritance
June 3, 2010 1 Comment
Now that we created a base Javascript class in the first post, let’s inherit from it to get a derived class.
// Define the derived function (remember there is no 'class' keyword in Javascript) function MyDerivedClass() { } // Derive from MyClass, equivalent to –> public class MyDerivedClass : MyClass MyDerivedClass.prototype = new MyClass(); // Create an instance of the derived class var myderivedClass = new MyDerivedClass(); // Get the public field alert(myderivedClass.aPublicField); // Call the public method alert(myderivedClass.aPublicMethod());
Woah! That was simple! Notice that MyClass’s private methods and the runtime field (aRuntimeField) we gave to MyClass in the last post is not available to MyDerivedClass.
Let’s override the base classe’s public fields and methods and see what happens,
// Define the derived function (remember there is no 'class' keyword in Javascript function MyDerivedClass() { // Override the base's public field this.aPublicField = "This is a public field of the type MyDerivedClass"; // Override the base's public method this.aPublicMethod = function() { return this.aPublicField; } } // Derive from MyClass, equivalent to –> public class MyDerivedClass : MyClass MyDerivedClass.prototype = new MyClass(); // Create an instance of the derived class var myderivedClass = new MyDerivedClass(); // Get the public field alert(myderivedClass.aPublicField); // Call the public method alert(myderivedClass.aPublicMethod());
You’ll see that the base classes public fields and methods have been overridden in the derived class.
We can obviously derive again,
// Derive from MyDerivedClass function MyDerivedDerivedClass() { // Override the base's public field this.aPublicField = "This is a public field of the type MyDerivedDerivedClass"; // Override the base's public method this.aPublicMethod = function() { return this.aPublicField; } } // Derive from MyDerivedClass, equivalent to –> public class MyDerivedDerivedClass : MyDerivedClass MyDerivedDerivedClass.prototype = new MyDerivedClass(); // Create an instance of the derived class var myderivedderivedClass = new MyDerivedDerivedClass(); // Call the public method alert(myderivedderivedClass.aPublicField);
Pingback: Javascript Concepts Simplified « I.Net