Creating Objects with JavaScript
This is just the basic idea, I’m not going to get into inheritance. There are more advanced things you can do but I’ll go over them separately if I get time.
Writing objects in JavaScript is really dead simple! You write them like a function, and because JavaScript is by it’s own nature an Object oriented language the rest just falls into place.
{
this.somePublicProperty = 42;
this.anotherPublicProperty = 10;
var somePrivateProperty = 5;
this.multiplyPublic = function()
{
return this.somePublicProperty * this.anotherPublicProperty;
}
this.getSomePrivateProperty = function()
{
return somePrivateProperty;
}
}
//Now we can play with it like other JavaScript Objects
var Obj = new myObject();
document.write(Obj.somePublicProperty); //42
document.write(Obj.anotherPublicProperty); //10
document.write(Obj.somePrivateProperty); //ERROR!! It’s private we can’t see it
document.write(Obj.multiplyPublic()); //420
document.write(Obj.getSomePrivateProperty()); //5
That’s it really that’s the basics. You just prefix var names with “this.” instead of “var ” if they need to be accessed from outside. Private properties use “var” like you’ve always done with functions and methods are defined inline.
To create a new object just use the “new” keyword like you do with Image() or Array(). Easy yes?
So where’s the constructor? Ah ha! There isn’t one as such. Reason? The object itself is a function; you place any constructor code directly inside it!
{
this.username = username;
alert(‘You are ‘ + username);
/*
other stuff here
*/
}
Private methods just get nested in as functions too.
I should point out another way to define you properties and methods, an also ways to extend the object. The way we do this is to use a special property called “prototype”. All objects have this - even the built in ones such as “Array()” and “Image()”.
{
//Lets not do anything yet, we’ll do it later!
}
myObject.prototype.someProperty = 42;
myObject.prototype.getSomeProperty = function()
{
return this.someProperty;
}
var Obj = new myObject();
document.write(Obj.getSomeProperty()); //42
One thing to remember with prototype however is that you have no access control. i.e. Everything you create will be public. It is very useful for extending built-in objects though. For example you could write a new method for a javascript array. Let’s write getKey(valueName) which will tell us the key at which a certain value occurs.
{
for (var x in this)
{
if (this[x] == valueName) return x;
}
}
var foo = new Array(1, 2, 3, 4);
alert(foo.getKey(3)); //2
I’ll write another tutorial on some of the fancier things over the next couple of weeks but I’m pretty busy with other things so I just do bits and pieces when I get some time. Here’s a task - write an object that can load in another object and run methods in it! I’ll cover that next week but you can probably see how it would be done from what you’ve seen above :)
No Responses to “Creating Objects with JavaScript”
No comments yet