Javascript is a prototype-based language. It works on objects. Each object has an internal property called prototype,from which other objects inherit properties. It extends the functionalities of class. The prototype object has a prototype object of its own, and so on this is referred to as the prototype chain.
When we request for a property that the object does not contain,then javascript looks for it through the prototype chain until it finds it till it reaches the end of the chain. This behaviour enable us to implement inheritance through classes.
Here is an example to depict inheritance using prototype:-
Well start with a constructor method
var Person = function(firstName)
{
this.firstName = firstName;
};
// Add a couple of methods to Person.prototype
Person.prototype.coding = function(){
console.log("I am coding!");
};
Person.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName);
};
// Define the Student constructor
function Student(firstName, subject) {
// Call the parent constructor (using Function#call)
Person.call(this, firstName);
// Initialize our Student-specific properties
this.subject = subject;
};
We are using a call function that lets us call another function and specify the value of this within that function.
// Create a Student.prototype object that inherits from Person.prototype.
Student.prototype = Object.create(Person.prototype);
// Set the "constructor" property to refer to Student
Student.prototype.constructor = Student;
// Replace the "sayHello" method
Student.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName + ". I'm studying "
+ this.subject + ".");
};
// Add a "Thankyou" method
Student.prototype.Thankyou = function(){
console.log("Thankyou!");
};
function new_class()
{
var student1 = new Student("Neha", "Physics");
student1.sayHello();
student1.coding();
student1.Thankyou();
}
In the above code when we request student.sayHello, JavaScript has to travel down the prototype chain until it finds the sayHello property inherited from Person.
0 Comment(s)