Object Orientation In JavaScript III [Overloading and Overriding]
let's start with Overriding it's easier to explain
of course you must have the idea of inheritence in your mind well if you have missed it check back here first
1: function superClass (){ 2: this.superClassMember = function(){ 3: alert ('this is executed from the Super Class'); 4: }
5: }
6:
7: // and then
8:
9: function subClass(){ 10: // the next two lines are the inheritence implementation
11: this.inheritence = superClass;
12: this.inheritence();
13:
14: // then the rest of the sub class implemenation
15:
16: this.subClassMember = function (){ 17: alert ('this is executed from the Sub Class'); 18: }
19: }
now just add this to the definition of the subCalss
1: function subClass (){ 2: ...
3: ..
4: //the next 3 lines are the lines to be added
5:
6: this.superClassMember = fucntion(){ 7: alert ("this is the overriden member of the subClass") 8: }
9:
10: }
now when u create an instance of the subClass and execute the "superClassMemeber" the result would be the alert containing"this is the overriden member of the subClass"
like this
1: var subClassObj= new subClass();
2: //this runs the functionality in the subclass as it has
3: // been overriden
4: subClassObj.superClassMember();
and now for overloading, i can't really say that the same concept applies in JavaScript, but you can call the very same function with a different no of parameters and it wouldn't break, and also you can add extra parameters and use them inside that function
let's try optional parameters first
1: function multiply (firstNo,secondNo,thirdNo){ 2: result = firstNo * secondNo;
3: // then u check for the existence of the thirdNo
4: // like this
5: if (thirdNo){ 6: result = result * thirdNo
7: }
8: return result
9: }
now the above example can be called like this
1: mutiply(1,2,3);
2: //or
3: multiply(1,2);
or Accessing extra parameters: in the following snippet you'll find out that every function in JavaScript has a private attribute that is called "arguments" which is an array that contains all the values in the parameters call even if the function signature does not contain any parameters
1: function multiply(){ 2: var result=1;
3: for(i=0;i<arguments.length;i++){ 4: result = result * arguments [ i ] ;
5: }
6: }
let me give another example
1: function doSomething (operand,value){ 2: var expressionToEvaluate = value ;
3: for (i=2;i<arguments.length; i++){ 4: // note that the first parameter "operand"
5: // is accessed with its name and the rest are
6: // being accessed through the arguments Array
7: expressionToEvaluate+= operand + arguments [ i ];
8: }
9: return eval (expressionToEvaluate);
10: }
11:
12:
13: this can do another type of polymorphism :)
14: alert (doSomething('*',2,3,4,5)); 15: alert (doSomething('+',2,3,4,5));
this article is part of a series please check
part 1,
part 2