Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JavaScript: Adding methods to an object

An object in JavaScript has properties and methods associated with it. For example, see the following object 'employee', it has properties Firstname, lastName and id. It has methods
a.   setFirstName : sets the firstName of employee object
b.   setLastName : sets the lastName of employee object
c.   setId : sets the id of the employee object
d.   getDetails : return string representation of employee object.

var employee = {
firstName: "no_name",
lastName: "no_name",
id: "-1",

setFirstName: function(firstName){
this.firstName = firstName;
},

setLastName: function(lastName){
this.lastName = lastName;
},

setId: function(id){
this.id = id;
},

getDetails: function(){
return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
}
}

Note that I used this keyword inside the methods, When a function is called from the object, this becomes a reference to the current object. By using this, we can refer current object properties.

object.html






objects



"text/javascript">
var employee = {
firstName: "no_name",
lastName: "no_name",
id: "-1",

setFirstName: function(firstName) {
this.firstName = firstName;
},

setLastName: function(lastName) {
this.lastName = lastName;
},

setId: function(id) {
this.id = id;
},

getDetails: function() {
return "[firstName = " + this.firstName + ", lastName = " + this.lastName + ", id = " + this.id + "]";
}
}

employee.setFirstName("Hari Krishna");
employee.setLastName("Gurram");
employee.setId(1);

document.write(employee.getDetails());





Load above html in browser, you can able to see following text.

[firstName = Hari Krishna, lastName = Gurram, id = 1]


Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

JavaScript: Adding methods to an object

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×