Friday 11 October 2013

Start building your OOP JavaScript objects

Let's face it. Sometimes jQuery doesn't cut it. Either you don't want the user to download the library or it seems to be a sledgehammer to crack a nut. JavaScript has also matured into a great server-side language. Think of node.js. My example below uses OOP JavaScript for web interaction, but consider the concept on the server-side too.
Let's start with the HTML page:
<html>
<script src="alertster.class.js"></script>
<script>
var myalertster = new alertster('hello');
myalertster.sendit('goodbye');
</script>
</html>
Not too big is it? Essentially we are creating a new object called myalertster from a class called alertster which lies within a file called alertster.class.js. I am passing a couple of parameters here, but as you'll see from the contents of alertster.class.js (below), I've stuck a little error trapping in there too.
Now for alertster.class.js:
function alertster(message)
{
message = typeof message !== 'undefined' ? message : 'Default message';
this.m = message;
this.sendit = function(additional)
{
additional = typeof additional !== 'undefined' ? additional : 'Default additional message';
alert(this.m+"\n"+additional);
};
};
Easy!

No comments:

Post a Comment