Overriding JavaScript Function
Javascript supports overriding but not overloading. When you define multiple functions in Javascript and include them in the file then the last one is referred by the Javascript engine.
Original Javascript file which we refer:
- function Employee(name)
- {
- this.Name=name;
- }
-
- Employee.prototype.getgreeting=function(){
- return "Hello, "+this.Name;
- }
Now as per our requirement we want to override the getgreeting function. So we create a new file and use the below code to override this function and include both files in our index.html file.
- Employee.prototype.getgreeting=function(){
- return this.Name.toUpperCase();
- }
-
- var emp=new Employee("xyz");
- alert(emp.getgreeting())
Inheritance In JavaScript
Object-oriented programming languages like C# and Java support inheritance, and Javascript is also an object-oriented programming language so it supports inheritance.
The main purpose of inheritance is Code Reuse. In Java or C# we create a parent class and that inherits in the child class. But in Javascript, you can achieve this kind of functionality by using a prototype. So inheritance in Javascript is prototype-based. We can implement this object inheritance from another object.
-
- var Employee=function(name)
- {
- this.Name=name;
- }
-
- Employee.prototype.getname=function(){
- return this.Name;
- }
-
- var PermanantEmployee=function(salary){
- this.annualSalary=salary;
- }
-
- var emp=new Employee("Sagar Jaybhay");
- PermanantEmployee.prototype =emp;
-
- var per=new PermanantEmployee(3000);
- console.log(per.getname());
-
- document.writeln(per.getname());
In the above code, we create Employee as a constructor function and another constructor function which is a permanent employee.
Then we create an object of Employee and assign this object to the PermanentEmployee prototype object so properties in the employee constructor function can access a permanent employee object.
By using this code you can check whether it is an instance of Employee or not and the result is true.
Whatever method you added to parent constructor function is accessible to a permanent employee object.
hasOwnProperty method is used to determine if the property belongs to parent or child.
-
- var Employee=function(name)
- {
- this.Name=name;
- }
-
- Employee.prototype.getname=function(){
- return this.Name;
- }
-
- var PermanantEmployee=function(salary){
- this.annualSalary=salary;
- }
-
- var emp=new Employee("Sagar Jaybhay");
- PermanantEmployee.prototype =emp;
-
- var per=new PermanantEmployee(3000);
- console.log(per.getname());
-
- document.writeln(per.getname());
- document.writeln(per instanceof Employee)
-
- document.writeln("<br/>")
- document.writeln("annualSalary property : "+per.hasOwnProperty("annualSalary"))
-
- document.writeln("<br/>")
- document.writeln("Name property : "+emp.hasOwnProperty("Name"))