.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal

Home >> Code Snippets >> Javascript >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Creating Your Own Objects

Posted By:Abraham       Posted Date: August 31, 2010    Points: 10    Category: Javascript    URL: http://www.dotnetspark.com  

Creating Your Own Objects

There are different ways to create a new object:

1. Create a direct instance of an object The following code creates an instance of an object and adds four properties to it: personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; Adding a method to the personObj is also simple. The following code adds a method called eat() to the personObj: personObj.eat=eat;

2. Create a template of an object

The template defines the structure of an object: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } Notice that the template is just a function. Inside the function you need to assign things to this.propertyName. The reason for all the "this" stuff is that you're going to have more than one person at a time (which person you're dealing with must be clear). That's what "this" is: the instance of the object at hand. Once you have the template, you can create new instances of the object, like this: myFather=new person("John","Doe",50,"blue"); myMother=new person("Sally","Rally",48,"green"); You can also add some methods to the person object. This is also done inside the template: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; } Note that methods are just functions attached to objects. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname; } The newlastname() function defines the person's new last name and assigns that to the person. JavaScript knows which person you're talking about by using "this.". So, now you can write: myMother.newlastname("Doe").

Creating Your Own Objects


Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend