Last Updated: February 25, 2016
·
2.383K
· hpcwebdev

Javascript Custom Object Simple Example

2012-10-10 Updated all references to "Classes" to "Objects." I was referring the custom objects as classes. Which in Javascript is not the case. Javascript does not use classes, as was pointed out. My mistake! Thanks for the info, <a href="http://coderwall.com/avenger7x">avenger7x</a>

So I have been on a quest recently to improve my overall experience with Javascript. The latest endeavor is to build objects for my Javascript scripts. The code below is my "simple" Person object I built. The goal of this object is to add a person, figure out their age and ask them to say Hello.

function Person(p_name, p_year){

    this.name = p_name;
    this.age = this.getAge(p_year);
}

This simple function just takes two parameters: Name and Year of Birth. You will notice in this constructor there is another function called getAge. This function is added below:

Person.prototype.getAge = function(year){

var dObj = new Date();
var currentYear = dObj.getUTCFullYear();    
return currentYear - year;
}

By adding the getAge function under the Person object, we can now use it within the scope of the Person object. To declare a new Person object, we simply include the Person Javascript on the page and then call the constructor.

<script type="text/javascript" src="person.js"></script>
<script type="text/javascript">
      var personObj = new Person("Patrick", 1986);
</script>

This will now set up a new Person object with the name of Patrick and an age of 26 (as of this post.) It figured out the age from the setAge function I wrote using the Javascript Date Object object. One quick note about this, when passing the year, I am not passing it as a string. However, if someone accidentally used a string, it would return NaN. It would be a good idea to format the data before using it in the setAge function. However, this is a simple example and I would do that if I further developed this script.

Finally, I want this "Person" to say Hello and their age on my web page. To do this, I wrote another function within the Person object called sayHello.

Person.prototype.sayHello = function(){

    document.write("Hello my name is: " + this.name + "<br />");
}

I would then add this to my HTML page code:

<script type="text/javascript">
      var personObj = new Person("Patrick", 1986);
      personObj.sayHello();
      document.write("My age is: " + personObj.age + " years old.");
</script>

You notice that in addition to the sayHello() function, I also called the property age from the object in a document.write().

The result from the script should yield something like this:

Hello my name is: Patrick
My age is: 26 years old.

So this was my simple Javascript Object example. I hope you found this information useful. I am still learning more about this, so I'm sure there are many ways to improve this, but I believe this is a great first start.

Thanks!