Saturday 22 December 2018

How to add properties to an existing object type in JavaScript?

By adding the properties to the existing type prototype, you can add new properties to existing type.

function Employee(firstName, lastName, id){
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
}

/* Adding two new properties to the existing type Employee */
Employee.prototype.organization="ABC";
Employee.prototype.location="Bangalore";

Above statements add two properties organization, location to the Employee type.

Find the below working application.

HelloWorld.js
function Employee(firstName, lastName, id){
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
}

/* Adding two new properties to the existing type Employee */
Employee.prototype.organization="ABC";
Employee.prototype.location="Bangalore";

var emp1 = new Employee("Krishna", "Majety", 123);

console.log("firstName : " + emp1.firstName);
console.log("lastName : " + emp1.lastName);
console.log("id : " + emp1.id);
console.log("organization : " + emp1.organization);
console.log("location : " + emp1.location);


Output
firstName : Krishna
lastName : Majety
id : 123
organization : ABC
location : Bangalore

New properties are reflected to the objects that created after adding these new properties to types.

HelloWorld.js
function print_employee_information(emp){
  console.log("\n************************");
  console.log("firstName : " + emp.firstName);
  console.log("lastName : " + emp.lastName);
  console.log("id : " + emp.id);
  console.log("organization : " + emp.organization);
  console.log("location : " + emp.location);
}

function Employee(firstName, lastName, id){
  this.firstName = firstName;
  this.lastName = lastName;
  this.id = id;
}

var emp1 = new Employee("Krishna", "Majety", 123);
print_employee_information(emp1);

/* Adding two new properties to the existing type Employee */
Employee.prototype.organization="ABC";
Employee.prototype.location="Bangalore";

var emp1 = new Employee("Ram", "Gurram", 5678);
print_employee_information(emp1);


Output

************************
firstName : Krishna
lastName : Majety
id : 123
organization : undefined
location : undefined

************************
firstName : Ram
lastName : Gurram
id : 5678
organization : ABC
location : Bangalore




Previous                                                 Next                                                 Home

No comments:

Post a Comment