Wednesday, April 8, 2009

Introduction of Objects

Introduction

Welcome to the javascript objects. By now you should already have a firm grasp over javascript basics. Which you might be wondering what the heck they are. An object is the to me the equivalent of an OOP class. I'm sure you've heard of and used several objects before, most likely without even realizing it. Perhaps they will ring a bell:

*
* String
* Array
* Date
* Number

I'll go over how to modify the existing ones and how to create your own.


A bit more about the terms

Object - A class/constructor
Instance - A certain instance of an object
Property - A variable held by an instance/object
Method - A function held by an instance/object
this - It refers the instance inside of methods and properties.


Prototype:

Prototype is the key to being able to edit existing objects such as string or array. I'll start off with an example of a method:
Code:

String.prototype.tell = function()
{
alert(this);
}



Now, you first might be wondering what this does and how to use it. Which brings me to another example:
Code:

var example = 'This is an instance of a string.';
example.tell();



The output of example.tell() would be "This is an instance of a string." It simply alerts the value of the string. You might also question as to why it is example.tell() instead of String.tell(). The simple answer is this: When using objects you will most likely have several instances, since you will most likely want functions that work with the value of the instance.
One more example just to push you in the right direction:

Code:

Number.prototype.dbl = function(){
return this * 2;
}
var x = 5;
alert(x.dbl()) //Will alert 10




Creating your own objects...

Like last time I'm going to start with an example, it's fairly simple and you should be able to get the general idea of how it works:
Code:

function Person(first,last,age){
this.first = first; //Properties
this.last = last;
this.age = age;
this.greet = function() //Method
{
alert('Hello my name is '+this.first+' '+this.last+'.');
}
}
var john = new Person('John','Doe',35);
john.greet();
alert(john.age); //Alerts 35
var jill = new Person('Jill','Doe',64);
jill.greet();
alert(jill.age); //Alerts 64



There it is, a very simple custom object. The Person object has a total of 5 properties which are first, last, age, prototype, and constructor. Prototype and constructor are default properties included in every object. It has only has the one method of greet. Custom objects are used to make things go faster. Imagine if you had to do something like this for each person instead of using the Person object when you have 500 people:

Code:

var johnFirst = 'John';
var johnLast = 'Doe';
var johnAge = 35;
function johnGreet()
{
alert('Hello my name is '+johnFirst+' '+johnLast+'.');
}




Summary:

Overall javascript objects aren't all that tough. It just takes a bit of time to read and experiment with.

No comments:

Post a Comment