The constructor method
This method imitates the process of first defining a class and then afterwards instantiate an object. So the first thing we are going to do is to define the class. The syntax of creating a class is similar to what you have when defining a function. So let say we want to create a class called ‘webdevelopers’ you will then write
function webdevelopers()
{
}
Since a class is supposed to be a template that objects are created from; a list of the properties peculiar to that class must therefore be listed. To do that you write
function webdeveloper(identity,location,technologies,portfolio)
{
this.identity = identity;
this.location = location;
this.technologies = technologies;
this.portfolio = portfolio;
}
So the next thing to do is to create an object from this class. To illustrate let me use my friend who is a web developer as an example. Here are some of his characteristics;
• His name is Tim
• He stays in lagos
• Php is one of the technologies he uses
• Searchnigeria.info is part of his portfolio
So to model him as an object I will just write
var Tim = new webdeveloper(‘tim’ , ‘lagos’ , ‘php’, ‘searchnigeria.net’);
And so I have a ‘Tim’ object.
To see if the object is well created, try to access the listed properties. For example, including this:
alert(Tim.location);
Should result into an alert box with the message “lagos”
What about adding methods to your objects? That is also easy
i.e if I want a method that will write my name in an alert box, I will need to add the following code to the function that defines the webdevelopers class:
this.saymyname = function myfunction() {alert('dade');}
So whenever I call the method by writing ‘this.saymyname()’ the function ‘myfunction()’ will be executed and i will have my name shout at you from the alert box.
3 comments:
Thanks for the post. However you're not covering where to initialize the saymyname
Its Simple you have to add it inside class definition as follows:
function webdeveloper(identity,location,technologies,portfolio)
{
this.identity = identity;
this.location = location;
this.technologies = technologies;
this.portfolio = portfolio;
//As Its a instance method
this.saymyname = function myfunction() {alert('dade');}
};
Also it will be better to use Init Capitalization of function name that is going to be your constructor,in this case webdeveloper -->Webdeveloper.Although its just convention but you may prefer differently.
thank you for the post
Post a Comment