Almost all the Javascript objects are instances of Object. Every object inherits properties and methods from Object.prototype. The developer has the flexibility to add new properties and methods to objects. The following example shows how to use Prototypes in Javascript.
i. name
ii. salary
iii. age
It has one function / method that has been declared named "DisplayDetails()". Please note that we use "this" keyword to set up every property and method. In simple terms, "this" means the current object on which actions are called.
The above code will display "New Employee" as the output. As we are calling the method of the prototype, it will also return the following output:
Details of Employee
=============================
Name:New Employee
Salary:25000
Age:27
Also, we can add properties and methods dynamically to the objects after they are created. For e.g. in case we want to add a property to the Prototype dynamically, the following code will work:
function Person(name,salary,age){
this.name = name;
this.salary = salary;
this.age = age;
this.DisplayDetails = function(){
var name = "Details of Employee\n";
name+="=============================+\n"
name+="Name:"+this.name+"\n";
name+="Salary:"+this.salary+"\n";
name+="Age:"+this.age+"\n";
return name;
}
}
var person1 = new Person("New Employee",25000,27);
console.log("Name is:"+person1.name);
console.log(person1.DisplayDetails());
In the above example we created a new Prototype named "Person" which has the following properties:i. name
ii. salary
iii. age
It has one function / method that has been declared named "DisplayDetails()". Please note that we use "this" keyword to set up every property and method. In simple terms, "this" means the current object on which actions are called.
The above code will display "New Employee" as the output. As we are calling the method of the prototype, it will also return the following output:
Details of Employee
=============================
Name:New Employee
Salary:25000
Age:27
Also, we can add properties and methods dynamically to the objects after they are created. For e.g. in case we want to add a property to the Prototype dynamically, the following code will work:
Person.prototype.height="160 cm";
console.log(person1.height);
In case we want to add a method dynamically: Person.prototype.DisplayHeight = function(){
console.log("The height of the person is :"+this.height);
}
person1.DisplayHeight();
Happy Coding! | dhandrohit@gmail.com
Comments